I have this extension method:
public static bool In<T>(this T source, params T[] list)
{
return list.Contains(source);
}
Now I need to use the above method for a ushort. When I try
ushort p = 3;
if (p.In(1, 2, 3, 4, 5))
return;
The first line casts 3 to a ushort well. But when 3 is passed as a parameter, I get the error
‘ushort’ does not contain a definition for ‘In’ and the best extension method overload ‘Extensions.In(T, params T[])’ has some invalid arguments.
But this works:
ushort p = 3;
if (Extensions.In(p, 1, 2, 3, 4, 5))
return;
which is weird.
-
Why does it work with the second example, but not the first?
-
What’s a good alternative that would help me here? Since there are no literals for
shortorushortI’m failing to find a simpler alternative than manually casting each integer like this:ushort p = 3; if (p.In((ushort)1, (ushort)2, (ushort)3, (ushort)4, (ushort)5)) return;
First, let’s work out what the compiler infers
Tto be. Some parameters areushortand some areint.ushorthas an implicit conversion tointandintdoes not have an implicit conversion toushort, soTisint.The key here is in section 7.6.5.2 of the C# 4 specification (emphasis mine):
There is an implicit conversion from
ushorttoint, but not an identity, reference, or boxing conversion!So, the following are legal:
but the following are not:
Note that you can get the same error without generics if you define
Inas