Type-conversion operators generated from single-argument constructors #9249
Unanswered
naine
asked this question in
Language Ideas
Replies: 2 comments 2 replies
-
Could do that with a source generator: partial struct Foo
{
[Implicit]
public Foo(Bar bar)
{
// ...
}
}
// generated
partial struct Foo
{
public static implicit operator Foo(Bar bar) => new Foo(bar);
} |
Beta Was this translation helpful? Give feedback.
0 replies
-
I don't think conversion operators that are exactly the same as a constructor are that common. And, as you have shown, the syntax to declare them is one clear and fairly short line of code. Also, if this is a common pattern in your code, you could write a source generator to do this. So I personally don't see the value in adding this feature. |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
In C++, if a type declares a single-argument constructor without specifying the
explicit
keyword, the compiler may use that constructor for implicit type conversions and copy-initialization.I'd like to propose similar functionality to be added to C#, except unlike C++ it should be opt-in, not opt-out. It could be implemented by having the compiler automatically generate type-conversion operators.
For example:
For symmetry, we might also consider allowing explicit:
The presence of the implicit/explicit keyword on the constructor should not affect the constructor itself in any way. It is still callable directly as normal per its declared accessibility. The implicit/explicit keyword only prompts the compiler to auto-generate the type-conversion operator in addition. The compiler should raise an error if the keyword is applied to a constructor that does not have exactly one parameter. The compiler should also raise an error if a conflicting operator is declared explicitly.
Beta Was this translation helpful? Give feedback.
All reactions