C# – The Need for Explicit Type Conversion

cexplicittype conversion

Consider the following code:

DerivedClass drbObj = (DerivedClass)obj;

Here obj is of type Object and this is reasonable since Object is the base type of every Class in C#.

Here, since the type of derObj is defined at compile time, what is the need to explicitly use type conversion here. Can't the compiler predict on it's own that it will be of DerivedClass. I understand that, the Conversion type doesn't have to match the Derived type, but for practical purpose, it will only be as useful as the Derived type.

Could someone explain with a small, hypothetical example, as to why the Explicit Type Conversion is necessary when a reference of type Object is being assigned to a derived class.

From what I know, in C, there is no need to do perform Explicit type conversion from void* to any pointer and the compiler can handle it, based on the type of the pointer to which the converted value is being assigned.

Best Answer

The reason why you have to do this is pretty simple:

Because that's the way the language was designed.

While yes, the C# designers could have decided to infer that your intent was to cast obj based solely on your declaration, they chose not to do so, probably because such an inference would cause more problems than it solved.

I can think of two reasons why they might have chosen not to infer the cast to DerivedObj:

1) Because it's inconsistent. Though for assignment (as in your example) it may seem logical to perform the inference, there are a ton of situations you would need to perform the cast explicitly, and making the casting behavior consistent makes the language conceptually simpler. For example, let's say you were writing a piece of code that needed to set the obj's ID to 5, knowing ahead of time that it was a DerivedObj. You'd still have to do the cast:

((DerivedObj)obj).ID = 5;

2) Because it's dangerous. Performing the cast at assignment is an "are you sure?" kind of check which makes you think twice about what the object really is before assigning. I would say that's a feature of the language, and definitely not worth a special-case casting behavior just for assignment. In fact, if you really created obj by saying obj = new object() somewhere, the cast will fail anyway.

Related Topic