jeudi 6 juillet 2017

"Inline temporary variable" (IDE0019) fix causes syntax errors when used with interfaces

I'm getting an object from ViewData.Model in an ActionFilter, and I need to make sure it conforms to a given protocol. Here's an example:

object d = DateTime.Now;
IComparable c = d as IComparable;
if (c != null)
{
    //do stuff
}

int i = 1;
int a = 1 + i;

Visual Studio 2017 gives me an IDE0019 "Inline temporary variable" suggestion on the second line. Selecting it refactors the code to this:

object d = DateTime.Now;
if (d is IComparable c)
{
    //do stuff
}

int i = 1; // Line 35
int a = 1 + i;

I like this syntax, and I'd like to use it. There are no errors shown in the editor, but when building I get a litany of errors:

1>C:\Users\me\MyProject\MyFile.cs(31,34,31,35): error CS1026: ) expected
1>C:\Users\me\MyProject\MyFile.cs(31,35,31,36): error CS1002: ; expected
1>C:\Users\me\MyProject\MyFile.cs(31,35,31,36): error CS1513: } expected

Line 35 is the seemingly innocuous int declaration. It looks like the compiler is expecting a lot more syntax, but I can't figure out what. The generated code appears identical to this example from the documentation for is:

public int CompareTo(Object o)
{
    if (o is Employee e)
    {
        return Name.CompareTo(e.Name);
    }
    throw new ArgumentException("o is not an Employee object.");
}

How can I fix these errors? I'm on VS2017 (26430.14) and .NET Framework v4.0.30319.

Aucun commentaire:

Enregistrer un commentaire