I've learned to use implicit operators for my classes.
Now I want to do something like this:
public static implicit operator string(int val)
{
return "The value is: " + val.ToString(); // just an nonsense example
}
However this is wrong. Compiler says:
User-defined conversion must convert to or from the enclosing type
How can I workaround this?
My goal is to be able to run code like this:
int x = 50;
textbox1.Text = x; // without using .ToString() or casting
You can't add an operator outside of the class of either the parameter or the return type of the operator.
In other words: You can't add an operator that converts between two types that you both don't control.
The compiler error you get is very explicit about this:
User-defined conversion must convert to or from the enclosing type
So, what you are trying to achieve here is simply not possible.
Your best option probably is an extension method on int that performs the conversion and returns a string.
You might want to consider an alternative approach.
You could write an extension method on Control like so:
public static class ControlExt
{
public static void SetText(this Control self, object obj)
{
self.Text = obj.ToString();
}
}
Then your code would become:
int x = 50;
textbox1.SetText(x);
It would of course work with any type, not just ints:
textbox1.SetText(DateTime.Now);
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