C# has the as keyword, it is mainly used to cast object of one type to another, and if it fails it should return a null rather than crashing the program or throwing exception.
From MSDN documentation it states:
You can use the as operator to perform certain types of conversions between compatible reference types or nullable types. The as operator is like a cast operation. However, if the conversion isn’t possible, as returns null instead of raising an exception.
1 2 3 4 5 6 7 8 |
object obj = GetPersonObj(123); Person p = obj as Person; //using the as keyword if(p != null) p.FullName = p.FirstName + " " + p.LastName; Person p2 = (Person) obj; //this can throw an exception if the object is not a person |
Differences between as and cast ( ) and when to use it:
- Using “as“, I think the object is of the type, but if it isn’t give me a null, don’t crash the application.
- Using cast, I know the object is of this type, and if it isn’t then crash the application.
- Using is and cast is more costly than just using as
Leave A Comment