I want to ask how do we compare two types in C#.
My Scenario is:
Nullable<int> Rating;
int NeedCompareType;
Every time I compare these two, it will return false result.
There is anyway for me to return true in this case because int
type have in both lines.
My compare line is:
if(Rating.GetType() == NeedCompareType.GetType())
Edit: Actually this was my program code:
public object this[string propertyName]
{
get
{
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 this code is to cast the value that the Controller receive from the browser as String type, then I want to convert to String type to the proper type of an unknown yet
property of the model (in this case that was the public Nullable<int> Rating { get; set; }
).
As you know I want when the propertyName = "Rating"
, it should execute the 2nd if statement, but it will not because the typeof(int)
and typeof(Nullable<int>)
will be different.
Sorry for my bad english
Actually, this line:
if(Rating.GetType() == NeedCompareType.GetType())
would always either go into the condition, or throw a NullReferenceException
- because Rating.GetType()
will box Rating
to either a boxed Int32
or a null reference.
Now if you're saying you want to compare typeof(int)
and typeof(Nullable<int>)
you could use:
public bool SomewhatEqual(Type t1, Type t2)
{
return t1 == t2 ||
t1 == Nullable.GetUnderlyingType(t2) ||
Nullable.GetUnderlyingType(t1) == t2;
}
Now that we've seen the code you're actually interested in, it sounds like you just want to treat each property with a nullable type as if it were non-nullable. That's easy:
set
{
PropertyInfo property = GetType().GetProperty(propertyName);
Type type = property.GetType();
// Treat nullable types as their underlying types.
type = Nullable.GetUnderlyingType(type) ?? type;
// TODO: Move this to a static readonly field. No need to
// create a new one 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);
}
}
See more on this question at Stackoverflow