The 'implicit' operator in C#
Did you know that in a class you can do something like:
Now class type1 will be automatically converted into type2 when used as such.
Example:
with this class all these statements are correct:
if the word implicit would have been explicit, then the compiler would have required you to cast nb to bool first:
Add to this Equals, ToString and == overide and you have a nice boolean type that allows for null values.
Update:
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:
while this would work:
Second of all, an object like the one above can in NET 2.0 be easily formed with nullable types:
bool? nb;
public static implicit operator type2(type1 value) {
return value.ToType2();
}
Now class type1 will be automatically converted into type2 when used as such.
Example:
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) {
internalBool=value;
}
public static implicit operator bool(NullBoolean) {
return internalBool;
}
}
with this class all these statements are correct:
NullBoolean nb=null;
nb=NullBoolean.True;
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.
Update:
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;
Comments
Be the first to post a comment