C # Explicit Operators and Inheritance

I'm sure this is a stupid question, but why doesn't the following code invoke an explicit statement to create on the MyBool child class?

public class DataType { public static explicit operator bool(DataType D) { return false; } public static explicit operator DataType(bool B) { return new DataType(); } } public class MyBool : DataType { public bool Value; public MyBool() { Value = false; } public static explicit operator bool(MyBool B) { return B.Value; } public static explicit operator MyBool(bool B) { return new MyBool() { Value = B }; } } 

then

 List<DataType> Types = new List<DataType>(); Types.Add(new MyBool() { Value = true }); Types.Add(new MyBool() { Value = false }); foreach (DataType T in Types) { bool Value = (bool)T; MessageBox.Show(Value.ToString()); } 

Produces output: false, false

Is the only option for writing functions on each class instead of explicit operator functions?

+8
c # operator-overloading
source share
2 answers

why the following code does not call an explicit statement to cast to a child class of MyBool?

Since the functions of the static operator are therefore also not virtual , and therefore their purpose is resolved at compile time, and not at run time. This is the expected behavior.

If you want to have polymorphic transform operators, you can call virtual functions inside the operators:

 public abstract class DataType { public static explicit operator bool(DataType D) { return D.DoCastToBool(); } public static explicit operator DataType(bool B) { // We haven't got an instance of our class here. // You can use a factory method pattern to emulate virtual constructors. } protected abstract bool DoCastToBool(); } 
+15
source share

Operators are overloaded, not overridden — in other words, choosing which implementation to use at compile time. The compiler only knows about T as a DataType , so it calls the statement in a DataType .

One option is to remove the statement from MyBool , but add a virtual method to the DataType , allowing polymorphic behavior:

 public class DataType { public static explicit operator bool(DataType D) { // TODO: Decide how you want to handle null references return D.ToBoolean(); } protected virtual bool ToBoolean() { return false; } } public class MyBool : DataType { // ... protected override bool ToBoolean() { return Value; } } 

Please note that this will not work for converting from bool to DataType , as in this case we do not have information about which subtype of DataType you really want to create.

(Side note: your code will be easier to track if you used the usual .NET naming conventions.)

+2
source share

All Articles