#1,057 – Custom Explicit Conversions
March 20, 2014 2 Comments
You can define both implicit and explicit custom conversions for a type that you author.
In the code fragment below, we’ve defined an implicit conversion from int to Dog and an explicit conversion from Cow to Dog.
// Implicitly convert from int to Dog public static implicit operator Dog(int value) { return new Dog(string.Format("Dog-" + value.ToString()), value); } // Explicitly convert from Cow to Dog public static explicit operator Dog(Cow cow) { return new Dog(string.Format(cow.Name + " IWasACow"), cow.Age); }
We can now do the following:
Cow someCow = new Cow("Bessie", 3); // Implicit conversion from int to Dog Dog anotherDog = 42; // Explicit conversion from Cow to Dog Dog nowADog = (Dog)someCow;
If we try assigning a Cow instance to a variable of type Dog without the cast operator, we’ll get a compile-time error indicating that there is no implicit conversion between Cow and Dog.