c# - Implementing IComparable<> in a sealed struct for comparison in a generic function -


i have c# .net 2.0 cf application i'm validating return value object. cannot modify structure or function returns it.

/// structure returned function object under test public struct sometype {     int a;     int b;     char c;     string d;      public static sometype empty { { return new sometype(); } } }  /// pretend function in object under test static sometype functionundertest() {     return sometype.empty; } 

since may have many functions returning many different types, wanted use generic comparison function. open modification.

static bool compare<t>(validationtypes validatecond,     t actualvalue,     t expectedvalue) t : system.icomparable<t> {     switch (validatecond)     {         case validationtypes.equal:             return actualvalue.compareto(expectedvalue) == 0;         case validationtypes.notequal:             return actualvalue.compareto(expectedvalue) != 0;         case validationtypes.lessthan:             return actualvalue.compareto(expectedvalue) < 0;         // more interesting things...     }     return false; } 

but, means structure returned function under test has implement system.icomparable<> interface. thinking this, won't work since structs sealed, should give idea of i'm looking for:

/// our test creates custom version of structure derives /// system.icomparable<> interface. public class sometypeundertest : sometype, system.icomparable<sometypeundertest> {     #region icomparable<sometypeundertest> members      public int compareto(sometypeundertest other)     {         // insert comparison function between object ,          return 0;     }      #endregion } 

thus, use this:

bool res = type<int>(validationtypes.equal, 1, 2);  bool res2 = type<sometypeundertest>(validationtypes.equal,      new functionundertest(),      new sometype.empty); 

please, let me know if has suggestions on how this.

thanks, paulh

have thought implementing icomparer<t> interface structure?

the type wouldn't implement comparisons itself. when want compare 2 values, use icomparer<t> instance instead.

int result1 = comparer<int>.default.compare(1, 2);                          // default comparer defaults                          // icomparable<t>.compareto  int result2 = new sometypecomparer().compare(funcundertest(), sometype.empty); 

Comments

Popular posts from this blog

ASP.NET/SQL find the element ID and update database -

jquery - appear modal windows bottom -

c++ - Compiling static TagLib 1.6.3 libraries for Windows -