Use of “as” keyword as for casting in C#


The keyword as doesn’t throw an exception if it fails to complete the casting operation.

Instead it will return null.

Other casting operations will throw an exception when the provided value cannot be casted.

Since the “as” keyword sets or returns “null” value when it fails, the variable you use must be of a reference type or nullable in order to be used with the as keyword. For example, following operation will not be suitable as int is not a nullable type.

int Year = rowYM["year"] as int; // the compiler will reject this because int is non-nullable value type

string FName = dt.Rows[0]["fname"] as string; // this works because string is a reference type

// c# - use of keyword as in csharp

Was this post helpful to you? How can I improve? – Your comment is highly appreciated!

Cassian Menol Razeek

This entry was posted in C#.Net and tagged , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *