-2

I'm studying some open source codes and converting them from visual studio version 2017 to 2015.

But I don't know how to convert any code.

I think there is a problem with the declaration of local variables in conditional statement.

This code

public static void ManageToolActivation(this IMachineElementViewModel vm, bool value)
        {

            if (vm is ToolHolderViewModel thvm)
            {
                thvm.ActiveTool = value;
            }
            else
            {
                foreach (var item in vm.Children)
                {
                    var child = item as MachineElementViewModel;

                    child.ManageToolActivation(value);
                }
            }
        }

causes

The name 'thvm' does not exist in the current context

ToolHolderViewModel is a name of other project(class).

It works in visual studio 2017 but not in visual studio 2015. I think there's a problem with declaring variables in conditional statements.

How can I modify this code to work?

Thomas Weller
  • 55,411
  • 20
  • 125
  • 222
Irene A
  • 3
  • 2
  • 1
    What exactly is the problem? Do you get any error messages? – Matt U Jun 24 '21 at 04:34
  • try this....if (vm is ToolHolderViewModel) { vm.ActiveTool = value; } – Amit Verma Jun 24 '21 at 04:34
  • The error message I received is as follows. 'The name 'thvm' does not exist in the current context' – Irene A Jun 24 '21 at 04:36
  • Thank you Amit Verma. I tried it on your advice, but it doesn't work... – Irene A Jun 24 '21 at 04:41
  • 1
    Amit is basically right, but you still need a cast. "It doesn't work" is (again) no useful error description. – Thomas Weller Jun 24 '21 at 04:42
  • I followed Amit's advice and got the following error message. : 'IMachineElementViewModel' does not contain a definition for 'ActiveTool' and no extension method 'ActiveTool' accepting a first argument of type 'IMachineElementViewModel' could be found (are you missing a using directive or an assembly reference?) – Irene A Jun 24 '21 at 04:47

1 Answers1

2

What you have here is Type testing with pattern matching, which is a feature of C# 7.0.

The code

variable is SomeType castedVariable

is a shortcut for

if (variable is SomeType)
{
    SomeType castedVariable = variable as SomeType;
}

Applied to your case:

if (vm is ToolHolderViewModel)
{
     ToolHolderViewModel thvm = vm as ToolHolderViewModel;
     thvm.ActiveTool = value;
}

While I doubt backporting a project to an older version of Visual Studio is beneficial, you might also try to make VS 2015 support C# 7.0.

Thomas Weller
  • 55,411
  • 20
  • 125
  • 222