Mike
Mike

Reputation: 153

Interview question on C# implicit conversion

I have been given a sample statement:

MyClass myclass = 3;

How is it possible to make this a valid statement? What code do I need to include in MyClass to support the implicit conversion from an int?

Upvotes: 14

Views: 785

Answers (5)

Anton Gogolev
Anton Gogolev

Reputation: 115711

Here's how:

public class MyClass
{
    public static implicit operator MyClass(int i)
    {
        return new MyClass(i);
    }
}

This uses C# feature called implicit conversion operator.

Upvotes: 6

Daniel Brückner
Daniel Brückner

Reputation: 59645

Just implement an implicit conversion operator.

Upvotes: 0

Simon P Stevens
Simon P Stevens

Reputation: 27499

You need to overload the implicit constructor operator:

public static implicit operator MyClass (int rhs)
{ 
    MyClass c = new MyClass (rhs);
    return c;
}

Upvotes: -1

bruno conde
bruno conde

Reputation: 48265

It's possible if MyClass has an implicit conversion from int.

Using Conversion Operators

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500055

You need an implicit conversion operator:

public class MyClass
{
    private readonly int value;
    public MyClass(int value)
    {
        this.value = value;
    }

    public static implicit operator MyClass(int value)
    {
        return new MyClass(value);
    }
}

Personally I'm not a huge fan of implicit conversions most of the time. Occasionally they're useful, but think carefully before putting them in your code. They can be pretty confusing when you're reading code.

On the other hand, when used thoughtfully, they can be amazingly handy - I'm thinking particularly of the conversions from string to XName and XNamespace in LINQ to XML.

Upvotes: 19

Related Questions