Click here to Skip to main content
11,648,094 members (65,787 online)
Click here to Skip to main content

Tagged as

Casting Restrictions ???

, 30 Jul 2010 CPOL 3.5K 1
Rate this:
Please Sign up or sign in to vote.
About casting restrictions

We all know that the runtime can detect the actual type of a System.Objectinstance. The primitive data types provided by the runtime are compatible with one another for casting (assuming that we do not truncate the values). So if I have an int, it can be cast to longor ulong. All that is fine. Watch this:

interface IAppDataTypeBase
   // Other methods

Since IAppDataTypeBaserepresents the mother of all types of data in my application, I have made GetValueto return the value as object (I could have used generics, that is for another day!).

IAppDataTypeBase longType = GetLongInstanceFromSomeWhere();
int i = (int)longType.GetValue();

So are we discussing any problems here? Yes, we are. The problem is that the value returned by GetValue- System.Object- despite being inherently long cannot be cast to an int. It would result in an 'Specified cast is invalid' exception. If an object is one of the primitive types, it can only be cast to its actual type. In the above case, the object returned by GetValuecan only be cast to long, and nothing else. The user defined data types do not have this restriction if the base type and target type are related.

class X { };
class DX : X { };
class Y { };

If GetValuereturns an instance of DX, it can be cast to X or any of its base interfaces (if any). The same goes good for structs too.

So why do we have this casting restriction for the primitive types? Was this unintentional or is there an advanced CLR internals web page somewhere talking about this? Probably fixed in C# 4.0? Until I learn why, the question is open.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Vivek Ragunathan
Software Developer (Senior)
United States United States
No Biography provided

You may also be interested in...

Comments and Discussions

-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150804.4 | Last Updated 30 Jul 2010
Article Copyright 2010 by Vivek Ragunathan
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid