When making a string in C#, you'd do string foo = "bar"; string being a class, and the value "bar" got passed to the class using the = operator. How was that done? Could you do this in your own class?
I know this is doable in C++ as such.
class someClass {
public:
someClass(int someInt) {
// Do Stuff
}
};
int main() {
someClass classInst = 123;
}
But what would be the C# equivalent?
There are two parts to this question:
String literals
The expression "bar" is already a value of type string. The assignment operator here is just copying the reference, as it does for anything else. String literals cause string objects to be created where possible (but reused, so if you have that code in a loop, there's only a single string object). There's some subtlety here for interpolated string literals around FormattableString, but I'll ignore that for the purpose of this question.
Creating your own literal-like syntax
You can't make the assignment operator implicitly call a constructor directly, no. You could add an implicit conversion from int to SomeClass, but I would generally discourage that.
Here's a complete example in case you really want to do it, but it's really not idiomatic. By the time you have implicit conversions, you make it harder to reason about overload resolution for example - and anyone reading your code has to know that there is a user-defined implicit conversion.
using System;
class SomeClass
{
public int Value { get; }
public SomeClass(int value) => Value = value;
public static implicit operator SomeClass(int value) =>
new SomeClass(value);
}
public class Program
{
static void Main()
{
SomeClass x = 123;
Console.WriteLine(x.Value);
}
}
Note that if the target-typed new feature comes to pass in C# 8, you'd be able to write:
SomeClass x = new(123);
... so you'd at least save the duplication there, even for fields.
You can define implicit conversions between the two types: int and SomeClass like below:
// User-defined conversion from SomeClass to int
public static implicit operator int(SomeClass someClass)
{
return someClass.SomeInt;
}
// User-defined conversion from int to SomeClass
public static implicit operator SomeClass(int someInt)
{
return new SomeClass(someInt);
}
Those methods should be defined in SomeClass declaration.
For more information about implicit conversion check this link.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With