In this blog I am going to explain difference between direct casting (normal typecasting), IS and AS operator in C#. In C#, we can type cast data from one data type to another data type using below methods:
2. Using AS operator: AS operator tries to cast an object to a specific type. It returns null on conversion failure instead of raising an exception.
3. Direct casting or normal typecasting: Direct casting or normal typecasting is most common way of casting one object to another data type. However it throws InvalidCastException exception if casting can’t be done.
Comments and suggestions are most welcome. Happy coding!
- Using IS operator
- Using AS operator
- Direct casting or normal typecasting
class Program { static void Main(string[] args) { object number = 6.3; //Check if number can be cast to int if (number is int) { Console.WriteLine("Number can be cast to int"); } else { Console.WriteLine("Number cannot be cast to int"); } } }Above code will print "Number cannot be cast to int" as number = 6.3 is a float value.
2. Using AS operator: AS operator tries to cast an object to a specific type. It returns null on conversion failure instead of raising an exception.
class Program { static void Main(string[] args) { object obj = new object(); obj = 16; string str = obj as string; // str == null if (str != null) { Console.WriteLine("Value is " + str); } else { Console.WriteLine("Value is null"); } } }Above code will print "Value is null".
3. Direct casting or normal typecasting: Direct casting or normal typecasting is most common way of casting one object to another data type. However it throws InvalidCastException exception if casting can’t be done.
class Program { static void Main(string[] args) { object obj = new object(); obj = 16; string str = (string)obj; // throws InvalidCastException exception if (str != null) { Console.WriteLine("Value is " + str); } else { Console.WriteLine("Value is null"); } } }Above code will throw InvalidCastException exception at run time.
Comments and suggestions are most welcome. Happy coding!
0 comments :
Post a Comment