Home > Software design >  Check type in C# 5.0 as in C# 7.0
Check type in C# 5.0 as in C# 7.0

Time:04-03

I'm following this tutorial, and at 16:16 it uses the following condition checking, which is a way to do it in C# 7.0 as far as I know.

if(Application.Current.MainWindow is MainWindow mainWindow)
{
    mainWindow.Start_Btn.Ischecked = false;
}

My question here is how to do the same using C# 5.0.

I've tried stating a variable of the type before the if statement but with no results, and to be honest I don't have much idea of how to do it.

MainWindow mw;
        
if(Application.Current.MainWindow is mw)
{
    mw.Start_Btn.Ischecked = false;
}

Edit: I have already checked the documentation (here and here), but it all refers to C# 7.0, and I'm trying to do it in 5.0 because some limitations I have at the moment.


Another edit: Same result can be obtained by

var window = (MainWindow)Application.Current.MainWindow;
window.Start_Btn.IsChecked = false;
window = null;

It doesn't check the type of Application.Current.MainWindow with a fancy declaration pattern inside an if statement, but it kind of works.

CodePudding user response:

The way you see in the tutorial is pattern matching. Unfortunately, as you said, it is a newer syntax.

With older C# versions, you should do it like this:

MainWindow mw = Application.Current.MainWindow as MainWindow;
        
if (mw != null)
{
    mw.Start_Btn.Ischecked = false;
}

With this, you are trying to get Application.Current.MainWindow as a MainWindow. If it is of type MainWindow, mw variable will contain the object Application.Current.MainWindow in it (reference of it, of course). Otherwise, mw variable will be null. This is why the null checking works.

Actually, this pattern was so common in older applications written in C#, so that Microsoft added the pattern matching syntax to shorten it and make it more readable.

For more info: Pattern matching overview

  • Related