Sunday, August 7, 2016

IS vs AS

IS To check is the date type ?

object i = "abcd";

if(i is string)
   Console.WriteLine(i +" is string");.


AS to convert object to datatype, want to support nullable datatype.

object k = 1234;
int? x = k as int?;


  • obj.ToString() - this is a call to the ToString() method of the object. The object returns a string as it was programmed to.
  • obj as string - this is an attempt to convert the object to a string, which may or may not fail (if it fails, the result is null), no exception will be thrown.
  • (string)obj - this is an explicit cast of obj to the type string, you are telling the compiler that obj is a string. If obj is not a string type, you will get a cast exception.
  • Convert.ToString(obj) - This is an explicit call to the Convert class to return a string representation of obj.

No comments:

Post a Comment