Get Help:Ask a Question in our Forums|Report a Bug|More Help Resources
Last post May 04, 2012 03:19 PM by bobwhite
May 03, 2012 02:50 PM|LINK
Why a code does not work and b. works
Int32 gvPk = GvContact.SelectedDataKey.Value as Int32 ;
Error .....The as operator must be used with a reference type or nullable type ('int' is a non-nullable value type)
Int32 gvPk = (Int32)GvContact.SelectedDataKey.Value; // this works
May 03, 2012 03:14 PM|LINK
a does not work because... when using as operator, it requires that the value which is being typed to some variable is nullable...
i.e. what if value of GvContact.SelectedDataKey.Value is null... in that case null could not be converted to int32... hence, error
in more detail.... as keyword is expression of type
expression is type ? (type)expression : (type)null
so, it returns null if value cannot be converted to destnation type... hence, it is required that the destination type should be nullable (int32 is not)
on contary, casting generates exception when it cannot convert one type to other....
due to nature of as keyword (which is, not to generate expcetion but return null value) both cast and as are different in nature and cause of your query
what happens if you use this?
Int? gvPk = GvContact.SelectedDataKey.Value as Int32 ;
hope this helps...
May 04, 2012 03:19 PM|LINK
Kedarrkulkarni, you realy made me understand this point. I even was not aware of this concept. Thanks alot