Home > Blockchain >  C# generic type limit to comparable primitive types like int, float, long, etc
C# generic type limit to comparable primitive types like int, float, long, etc

Time:01-09

This is sort of a combination of this and this questions. In the code below, if T: struct, then a==b cannot be used because structure's cannot be compared. If T: class, I cannot pass 1 and 2. If I only want to use comparable primitive value types like int, float, enum, long, etc, is there anything other than T: struct to limit the type of T?

public static bool Test<T>(T a, T b) where T: struct
{
    return a == b;
}

public static async Task Main()
{
    int a = 1;
    int b = 2;
    Test<int>(1, 2);
}

CodePudding user response:

you can use equals for compare types like int, float, enum, long

public static bool Test<T>(T a, T b) where T: struct
{
   return  a.Equals(b);
}
  • Related