I have asked a similar question before and this is more or less a follow up question. (C# Template Function: Cannot do non-virutal member lookup in 'T' because it is a type parameter)
I want to access a static abstract variable in a template function:
public static T AsType<T>(...) where T : ICode
{
//...
if(InterfaceCode != T.InterfaceCode) return null;
if(SubtypeCode != T.SubtypeCode) return null;
//...
}
with
public interface ICode
{
public static abstract ushort SubtypeCode { get; }
public static abstract ushort InterfaceCode { get; }
}
Whenever I try to run this code following exception is thrown:
'T.InterfaceCode' threw an exception of type 'System.BadImageFormatException'
I upgraded my project from .NET Core 3.1 to .NET 7 recently, because I wanted to use this "feature" (and it was a suggested solution to my last question)
Please let me know if you need more background information. Thanks for your help!
Reproduce-able example:
internal class Program
{
static void Main(string[] args)
{
AsType<Test>(1, 3);
}
public static T AsType<T>(ushort InterfaceCode, ushort SubtypeCode) where T : ICode
{
//...
if (InterfaceCode != T.InterfaceCode) return default(T);
if (SubtypeCode != T.SubtypeCode) return default(T);
//...
return default(T);
}
public interface ICode
{
public static abstract ushort SubtypeCode { get; }
public static abstract ushort InterfaceCode { get; }
}
public class Item : ICode
{
public static ushort SubtypeCode { get; } = 1;
public static ushort InterfaceCode { get; } = 2;
}
public class Test : Item
{
public static new ushort InterfaceCode { get; } = 1;
public static new ushort SubtypeCode { get; } = 3;
}
}
NOTE: It does NOT throw this error. It it only displayed in the debug environment (VS2022) when displaying T.InterfaceCode
.