Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicit operator for int?

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
like image 693
Kamil Avatar asked Jun 21 '26 14:06

Kamil


2 Answers

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.

like image 90
Daniel Hilgarth Avatar answered Jun 24 '26 04:06

Daniel Hilgarth


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);
like image 36
Matthew Watson Avatar answered Jun 24 '26 05:06

Matthew Watson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!