Convert.ChangeType() fails on Nullable Types
Untested, but maybe something like this will work:
string modelProperty = "Some Property Name";
string value = "Some Value";
var property = entity.GetType().GetProperty(modelProperty);
if (property != null)
{
Type t = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
object safeValue = (value == null) ? null : Convert.ChangeType(value, t);
property.SetValue(entity, safeValue, null);
}
Convert.ChangeType throwing Invalid Cast Exception for nullable int
I'm assuming Claim.Value
is of type Object
and you're dynamically converting here, you can't straight up convert an int
to an int?
via Convert.ChangeType
.
One option is to use Nullable.GetUnderlyingType
which will check if this is a nullable struct case, do the conversion via the underlying data type first, then cast to T
.
You'll also need to handle the null
scenario as well.
if (claim != null)
{
var conversionType = typeof(T);
if (Nullable.GetUnderlyingType(conversionType) != null)
{
if (claim.Value == null) //check the null case!
return default(T);
//use conversion to `int` instead if `int?`
conversionType = Nullable.GetUnderlyingType(conversionType);
}
return (T)Convert.ChangeType(claim.Value, conversionType);
}
How to use Convert.ChangeType() when conversionType is a nullable int
You can't do this since Nullable<T>
don't implement IConvertable
.
You can do this although.
string a = 24;
decimal? aAsDecimal = (decimal)Convert.ChangeType(a, typeof(decimal));
Might I also interest you in TryParse
?
Unable to ChangeType from string to int?
You'll need to write something like this:
var value = "00010";
short? w = value == null ? null : (short?)Convert.ChangeType("00010", typeof(short));
ChangeType
will not work with Nullable<T>
- and if we have a value for value
, we assume we have a value for the converted type
How to Convert a String to a Nullable Type Which is Determined at Runtime?
There are two problems.
Firstly, Convert.ChangeType
just plain does not support nullable types.
Secondly, even if it did, by boxing the result (assigning it to an object
), you'd already be converting it to a DateTime
.
You could special case nullable types:
string s = "2012-02-23 10:00:00";
Type t = Type.GetType("System.Nullable`1[[System.DateTime, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]");
object d;
if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>))
{
if (String.IsNullOrEmpty(s))
d = null;
else
d = Convert.ChangeType(s, t.GetGenericArguments()[0]);
}
else
{
d = Convert.ChangeType(s, t);
}
How can I fix this up to do generic conversion to NullableT?
public static T To<T>(this IConvertible obj)
{
Type t = typeof(T);
Type u = Nullable.GetUnderlyingType(t);
if (u != null)
{
return (obj == null) ? default(T) : (T)Convert.ChangeType(obj, u);
}
else
{
return (T)Convert.ChangeType(obj, t);
}
}
Related Topics
In C# Check That Filename Is *Possibly* Valid (Not That It Exists)
Declaration Suffix for Decimal Type
Appsettings Get Value from .Config File
How to "Flatten" or "Index" 3D-Array in 1D Array
Easiest Way to Read from a Url into a String in .Net
How to Detect Datagridview Checkbox Event Change
What Are the Limitations of SQLdependency
What Advantages of Extension Methods Have You Found
On Postback, How to Check Which Control Cause Postback in Page_Init Event
How to Sort an Observable Collection
C# Sending Mails with Images Inline Using Smtpclient
Is It Necessary to Manually Close and Dispose of SQLdatareader
C# Optional Parameters on Overridden Methods
Compare Version Numbers Without Using Split Function
Is Async Await Keyword Equivalent to a Continuewith Lambda
Suppressing "Is Never Used" and "Is Never Assigned To" Warnings in C#