Can anyone help?
I have some code that is shared between 2 projects. The code points to a model which basically is a collection of properties that comes from a db.
Problem being is that some properties use nullable types in 1 model and the other it doesn’t
Really the dbs should use the same but they don’t ..
so for example there is a property called IsAvailble which uses “bool” in one model and the other it uses bool? (nullable type)
so in my code i do the following
objContract.IsAvailble.Value ? "Yes" : "No" //notice the property .VALUE as its a bool? (nullable type)
but this line will fail on model that uses a standard “bool” (not nullable) as there is no property .VALUE on types that are NOT nullable
Is there some kind of helper class that i check if the property is a nullable type and i can return .Value .. otherwise i just return the property.
Anybody have a solution for this?
EDIT
This is what i have now….. i am checking HasValue in the nullable type version
public static class NullableExtensions
{
public static T GetValue(this T obj) where T : struct
{
return obj;
}
public static T GetValue(this Nullable obj) where T : struct
{
return obj.Value;
}
public static T GetValue<T>(this T obj, T defaultValue) where T : struct
{
return obj;
}
public static T GetValue<T>(this Nullable<T> obj, T defaultValue) where T : struct
{
if (obj.HasValue)
return obj.Value;
else
return defaultValue;
}
}
This is a little weird, but maybe you can use an extension method here:
They will work with nullable or regular types: