C# 7.0 Type Checking With Inlined Variable Assignment

In this post I cover a new feature for type checking in C# 7.


In this rather short post I’d like to share a really cool feature that was added in C# 7. I had written some code while working at home that did type checking with an is operator, and when I got to work the next day I couldn’t compile the same code, I tried to figure out why and it was because Visual Studio 2015 doesn’t support C# 7 (that, or I hadn’t updated it), so I ended up biting the bullet and installing 2017 and had zero issues in doing so (lucky me).

What this made me realize though is that the way I wrote this code took advantage of a new C# feature which none of my coworkers had even seen used yet, so I’d like to share said code with you.

Type checking with inlined variable assignment

Okay, so I’m not sure if that’s really what this feature is, but it’s the best way I can describe it. Say you have an event handler for a click event in Xamarin Android, and inside of it you do a type check as follows:

if(sender is PercentRelativeLayout parentView)
    position = (int)parentView.FindViewById(Resource.Id.someRandomId).Tag;

This is (mostly) the code I wrote that utilizes this new feature. So here, this event handler was implemented by several different views, and when the click event occurred, I needed to get the tag property, the problem is the view that held the tag differed from tablet to mobile, and so I needed to get the tag in a different way based on the type. What made this feature nice, is I can do a standard type check with an is operator on a generic object, and also assign a variable with the specified type for the inner portion of the if statement, rather than having to do the variable assignment in the if.


As simple as this feature is, it can really save you a decent amount of typing, and I haven’t seen many people talking about this smaller feature, so hopefully this was at least mildly interesting. Thanks for reading, until next time.

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: