TheDeveloperBlog.com


C# Implicit Keyword

Implicit operators allow certain conversions. With the implicit keyword, you allow any conversion from one class to another without any syntax. This makes it possible to assign one class instance to another. No cast expressions are needed.


Example. The implicit keyword is always used with the operator keyword. It requires a public static method that returns the type you want to convert to and accepts the type you are converting from.

Next: We provide a Machine class and a Widget class. Both classes have implicit conversion operators.

C# program that uses implicit operator

using System;

class Machine
{
    public int _value;
    public static implicit operator Widget(Machine m)
    {
	Widget w = new Widget();
	w._value = m._value * 2;
	return w;
    }
}

class Widget
{
    public int _value;
    public static implicit operator Machine(Widget w)
    {
	Machine m = new Machine();
	m._value = w._value / 2;
	return m;
    }
}

class Program
{
    static void Main()
    {
	Machine m = new Machine();
	m._value = 5;
	Console.WriteLine(m._value);

	// Implicit conversion from machine to widget.
	Widget w = m;
	Console.WriteLine(w._value);

	// Implicit conversion from widget to machine.
	Machine m2 = w;
	Console.WriteLine(m2._value);
    }
}

Output

5
10
5

The implicit operators here convert the Machine and Widget types by manipulating their _value fields. The Widget and Machine may be conceptually equal but have a different representation of their data.

And: The Widget's data is represented in an integer twice as large as the Machine.


Discussion. You should only use the implicit operator if you are developing a commonly used type. It is probably most useful for the .NET Framework itself. Numeric types can implement implicit conversions to some advantage.

Thus: Implicit is not something that most programs will require. It is worth knowing it exists, but not often useful.


Summary. The keyword implicit provides a way to implement conversions. With implicit, you can end up with some baffling programming scenarios where an implicit conversion is not reversible.

Typically: It would be best to keep more complicated conversions, and those that might fail, more apparent.

Explicit