Kamil
Kamil

Reputation: 13931

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

Upvotes: 3

Views: 2623

Answers (3)

Matthew Watson
Matthew Watson

Reputation: 109567

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);

Upvotes: 2

daryal
daryal

Reputation: 14919

You need to add implicit operator as a member of the class. Since you do not have control over int class; it is not possible to add an implicit operator to int class.

You may either write a wrapper for int or create a new extension method to convert int to string directly (which has already been defined as ToString()).

Upvotes: 1

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174299

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.

Upvotes: 6

Related Questions