How to compare 2 similar types in C# -
i want ask how compare 2 types in c#.
my scenario is:
nullable<int> rating; int needcomparetype; every time compare these two, return false result. there anyway me return true in case because int type have in both lines.
my compare line is:
if(rating.gettype() == needcomparetype.gettype()) edit: program code:
public object this[string propertyname] { { propertyinfo property = gettype().getproperty(propertyname); return property.getvalue(this, null); } set { propertyinfo property = gettype().getproperty(propertyname); iformatprovider culture = new system.globalization.cultureinfo("fr-fr", true); if (property.propertytype == typeof(system.datetime)) { property.setvalue(this, convert.todatetime(value, culture), null); } else if (property.propertytype == typeof(int)) { property.setvalue(this, int32.parse((string)value)); } else { property.setvalue(this, value, null); } } } the aim of code cast value controller receive browser string type, want convert string type proper type of unknown yet property of model (in case public nullable<int> rating { get; set; }).
as know want when propertyname = "rating", should execute 2nd if statement, not because typeof(int) , typeof(nullable<int>) different.
sorry bad english
actually, line:
if(rating.gettype() == needcomparetype.gettype()) would either go condition, or throw nullreferenceexception - because rating.gettype() box rating either boxed int32 or null reference.
now if you're saying want compare typeof(int) , typeof(nullable<int>) use:
public bool somewhatequal(type t1, type t2) { return t1 == t2 || t1 == nullable.getunderlyingtype(t2) || nullable.getunderlyingtype(t1) == t2; } now we've seen code you're interested in, sounds want treat each property nullable type if non-nullable. that's easy:
set { propertyinfo property = gettype().getproperty(propertyname); type type = property.gettype(); // treat nullable types underlying types. type = nullable.getunderlyingtype(type) ?? type; // todo: move static readonly field. no need // create new 1 each time iformatprovider culture = new cultureinfo("fr-fr", true); if (type == typeof(system.datetime)) { property.setvalue(this, convert.todatetime(value, culture), null); } else if (type == typeof(int)) { property.setvalue(this, int32.parse((string)value)); } else { property.setvalue(this, value, null); } }
Comments
Post a Comment