Last week I handled some object casting (DataGridView Columns Control casts) and I tried to cast a DataGridView TextBox Column to TextBox Control where I had a compile time error.
I found out that I should cast that TextBox Column to DataGridViewTextBoxColumn.
So how does the compiler decide if a type can be cast to another type (objects mostly)?
Next you have cases where the compiler lets you to do some casts but you will get a run time error.
All classes and types inherit from
object. Beyond that, it depends what class another class derives from. Using this, the compiler can determine if something can be cast from one to another. Some of these checks can be determined at compile-time, and some at run-time.Consider:
Now, give a reference to
E, I can safely cast toDorA(orobject). The compiler can tell that if I try and castEtoCorBno conversion is available, becauseEdoes not inherit from these 2, though they share a common base-class ofA.Now, consider if I have a reference to
Aand attempt to cast toE. This check cannot be performed at compile time and will fail at runtime if the instance in question is not actually an instance ofE(as, conceivably, it could be any of ‘A, B, C, D or E’).In addition to this, as Silvermind points out, we can provide our own
implicitandexplicitconversions where none exist. Consider this:The above allows us to go:
Without our implicit operator, this would (obviously) fail at compile time as no conversion exists from
Persontostringby default.Explicit operators are similar, but work the other way. This occurs if we wanted to cast a string to a person. So we could add the following explicit operator:
And now we can do this: