Tuesday, May 02, 2006

The 'implicit' operator in C#

Did you know that in a class you can do something like:
public static implicit operator type2(type1 value) {
return value.ToType2();

Now class type1 will be automatically converted into type2 when used as such.


public class NullBoolean {
private bool internalBool;

public static NullBoolean False {
return new NullBoolean(false);

public static NullBoolean True {
return new NullBoolean(true);
public NullBoolean(bool value) {

public static implicit operator bool(NullBoolean) {
return internalBool;

with this class all these statements are correct:
NullBoolean nb=null;
if (nb==true) MessageBox.Show("nb is true"); // no cast

if the word implicit would have been explicit, then the compiler would have required you to cast nb to bool first:

if ((bool)nb==true)...

Add to this Equals, ToString and == overide and you have a nice boolean type that allows for null values.

First of all implicit operators are a kind of a shortcut for casting. Sometimes this doesn't work, like in foreach loops. Sometimes a code like this will not work:
foreach (RowAdapter ra in dt.Rows) ...

while this would work:
foreach (DataRow dr in dt.Rows) {
RowAdapter ra=dt;...

Second of all, an object like the one above can in NET 2.0 be easily formed with nullable types:
bool? nb;