Skip to content

Implicit Typecasting in C#

25 February 2009

To enable a class to be implicitely typecasted to or from another class, create a public static method marked with the implicit operator keywords as follows:

public static implicit operator ClassToCastFrom(ClassToCastTo object) {...} 

Either ClassToCastFrom or ClassToCastTo must be the containing class. As an example, consider the class MyClass:

class MyClass
{
    private string value;

    public MyClass(string value)
    {
        this.value = value;
    }

    public override string ToString()
    {
        return value;
    }

    public static implicit operator int(MyClass myClass)
    {
        return 10;
    }

    public static implicit operator MyClass(int int32)
    {
        return new MyClass("From int " + int32);
    }
}

The class encapsulates a string and implements operators that enable it to be implicitely casted to and from int. When typecasted to int, it will become 10. When typecasted from int, its value will become “From int ” + the value of the int.

An example of implicit typecasting:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(20 + new MyClass(""));

        MyClass myInstance = 10;
        Console.WriteLine(myInstance.ToString());
    }

    static void ToInt32(int int32)
    {
        Console.WriteLine(int32);
    }
}

Notice that you can add an instance of MyClass to an int and you can assign an int to a MyClass instance.

We need  to call myInstance.ToString() instead of just passing myInstance to WriteLine because WriteLine doesn’t have an overload that accepts MyClass parameters. We would expect to upcast MyClass to object and call the inherited ToString() method but implicit typecasting takes precedency over upcasting, so calling Console.WriteLine(myInstance) would in fact convert it to an int instead of an object.

From → code complete

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: