Hi
Why a code does not work and b. works
a.
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)
b.
Int32 gvPk = (Int32)GvContact.SelectedDataKey.Value; // this works
Thanks
bob
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...
hope this helps...
Cheers!
KK
Please mark as Answer if post helps in resolving your issue
My Site
Marked as answer by bobwhite on May 04, 2012 03:19 PM
bobwhite
Member
701 Points
667 Posts
conversion from one data type to another....
May 03, 2012 02:50 PM|LINK
Hi Why a code does not work and b. works a. 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) b. Int32 gvPk = (Int32)GvContact.SelectedDataKey.Value; // this works Thanks bobkedarrkulkar...
All-Star
34545 Points
5554 Posts
Re: conversion from one data type to another....
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
http://msdn.microsoft.com/en-us/library/cscsdfbt(v=vs.71).aspx
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...
hope this helps...
KK
Please mark as Answer if post helps in resolving your issue
My Site
bobwhite
Member
701 Points
667 Posts
Re: conversion from one data type to another....
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
Bob