Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interview question on C# implicit conversion

Tags:

c#

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?

like image 410
Mike Avatar asked Aug 11 '10 11:08

Mike


People also ask

What is C language interview?

Fast Speed: C language is very fast as it uses a powerful set of data types and operators. Memory Management: C provides an inbuilt memory function that saves the memory and improves the efficiency of our program. Extensible: C is an extensible language as it can adopt new features in the future.


1 Answers

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.

like image 74
Jon Skeet Avatar answered Oct 02 '22 13:10

Jon Skeet