Reputation: 2780
I just upgraded to VS2017 but right off the bat my project can no longer be built, as I am getting a bunch of strange compiler errors that didn't exist when I was using VS15.
Errors such as:
Syntax Error; value expected
Invalid Expression Term '['
Invalid Expression Term 'byte'
Using the generic type requires 1 type arguments
using System;
using System.Runtime.InteropServices;
namespace Error
{
class Program
{
static void Main()
{
Array array2D = null;
if (array2D is Bgra <byte>[,])
{
}
}
}
public interface IColor { }
public interface IColor<T> : IColor
where T : struct
{ }
public interface IColor2 : IColor { }
public interface IColor2<T> : IColor2, IColor<T>
where T : struct
{ }
public interface IColor3 : IColor { }
public interface IColor3<T> : IColor3, IColor<T>
where T : struct
{ }
public interface IColor4 : IColor { }
public interface IColor4<T> : IColor4, IColor<T>
where T : struct
{ }
[StructLayout(LayoutKind.Sequential)]
public struct Bgra<T> : IColor4<T>
where T : struct
{
public Bgra(T b, T g, T r, T a)
{
B = b;
G = g;
R = r;
A = a;
}
public T B;
public T G;
public T R;
public T A;
public override string ToString()
{
return $"B: {B}, G: {G}, R: {R}, A: {A}";
}
public const int IDX_B = 0;
public const int IDX_G = 1;
public const int IDX_R = 2;
public const int IDX_A = 3;
}
}
Note that the exact same project compiles okay in VS15 and even VS13.
Upvotes: 13
Views: 1369
Reputation: 37225
C#7 extends the is
operator from pure type testing to what they call Pattern Matching.
The parser now seems to get confused by is
followed by array-of-generic. I'd try with parens around the type, but I cannot test this solution
if (array2D is (Bgra<byte>[,]))
Upvotes: 1
Reputation: 2624
According to my test, using as
operator works as expected in Visual Studio 2017.
So you can use
var tmp = array2D as Bgra<Byte>[,];
if (tmp != null) { ... }
Also, is
operator do works with simple array :
if (array2D is int[,]) { ... }
would also compile.
So it seems that the problematic case if when you have an array of generics. In fact, if you do something like
if (array2D is List<int>[,]) { ... }
you would get the compilation error.
Also the following code would compile
object something = null;
if (something is List<int>) { ... }
Thus, the only problematic case is when using an array of a generic type as the argument of the is
operator.
As a side note, I would generally prefer using as
operator to is
operator since usually you need a variable in the target type anyway.
Upvotes: 1