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

2009-01-06

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: