Thursday, April 23, 2020

Best Practice C# Make use of AS operator for casting object

Remember to use As operator, here is the simple reason to avoid unnecessary exception is thrown.

With exception


Student s= new Student();
Object o = s;

var newStudent=  (string)o;// Exception casting not possible

As Operator to rescue, AS operator returns null if not compatible else right conversion object type

Student s= new Student();
Object o = s;

var newStudent=  o as string;// Exception casting not possible




No comments :