I'm getting an object
from ViewData.Model
in an ActionFilter, and I need to make sure it conforms to a given interface. Here's an example:
object d = DateTime.Now;
IComparable c = d as IComparable;
if (c != null)
{
//do stuff
}
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) // Line 31
{
//do stuff
}
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 31 is the if
statement. 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.