Invalid cast from 'System.Int32' to 'System.Nullable`1[[System.Int32, mscorlib]]
You have to use Nullable.GetUnderlyingType
to get underlying type of Nullable
.
This is the method I use to overcome limitation of ChangeType
for Nullable
public static T ChangeType<T>(object value)
{
var t = typeof(T);
if (t.IsGenericType && t.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
{
if (value == null)
{
return default(T);
}
t = Nullable.GetUnderlyingType(t);
}
return (T)Convert.ChangeType(value, t);
}
non generic method:
public static object ChangeType(object value, Type conversion)
{
var t = conversion;
if (t.IsGenericType && t.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
{
if (value == null)
{
return null;
}
t = Nullable.GetUnderlyingType(t);
}
return Convert.ChangeType(value, t);
}
Invalid cast from System.Int32 to Nullable in case of Enum properties
Because you're dealing only with Enums
, you may simply change your code to this:
var safeValue = Enum.ToObject(t, dat[i]);
Invalid cast from 'System.Double' to 'System.Nullable`
Simply : that isn't a supported usage of Convert.ChangeType
. You need to give it the non-nullable form, i.e. double
. You could use Nullable.GetUnderlyingType
:
return value == DBNull.Value ? default(T) : (T)Convert.ChangeType(value,
Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T));
but this will have overhead; personally, I suspect it might be easier to use a Nullable<T>
specific method:
public static T? GetValue<T>(object value) where T : struct
{
if(value == null || value is DBNull) return null;
if(value is T) return (T)value;
return (T)Convert.ChangeType(value, typeof(T));
}
Or even better yet: use a an ORM or micro-ORM, so you don't need to do this stuff (also: they'll do a better job of it, by thinking about the type conversions during the meta-programming code, rather than the per-value execution code).
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);
}
InvalidCastException: Unable to cast object of type 'System.DBNull' to type 'System.Nullable`1[System.Int32]'
From DBNull Documentation:
DBNull
represents a nonexistent value, wherenull
denotes absence of
reference to the object.
To fix your issue,
Null check before changing value's type and then assign it to the variable
result.Add (
new GetActiveUserPackagesForOpenBillingPeriodResult {
Amount = (decimal) reader["Amount"],
AcceptanceActID = Convert.IsDBNull(reader["AcceptanceActID"]) ? null : (int?) reader["AcceptanceActID"],
PackageID = (int) reader["PackageID"],
UserID = (int) reader["UserID"],
AccountID = (int) reader["AccountID"],
HasChangedPackage = (bool) reader["HasChangedPackage"],
});
C# - Problems casting from System.String to System.NullableSytem.Int32 in bindings
tried to play around with this, and here's how I solved it - when creating the binding on the text box:
this.text_box.DataBindings.Add(new CustomBinding("Text", this.test, "some_int", false, DataSourceUpdateMode.OnPropertyChanged));
set the formatting flag to "true" (it's the third parameter).
once you do that, you don't need the custom binding anymore...I commented the code in OnParse out and it works. I use just a Binding object instead of CustomBinding, and it still works :)
check this blog for some details:
http://blog.jezhumble.net/?p=3
Related Topics
Factory Pattern in C#: How to Ensure an Object Instance Can Only Be Created by a Factory Class
Where Is Httpcontent.Readasasync
Forms' Does Not Exist in the Namespace System.Windows
MVC HTML.Beginform Different Url Schema
Difference Between Destructor, Dispose and Finalize Method
Getting Time Span Between Two Times in C#
Contextswitchdeadlock Was Detected Error in C#
What Is C# Analog of C++ Std::Pair
Execute Unit Tests Serially (Rather Than in Parallel)
In-Memory Database Doesn't Save Data
Database.Begintransaction VS Transactions.Transactionscope
Find and Return JSON Differences Using Newtonsoft in C#
Project a Can't Reference a Class in Project B
Intersect with a Custom Iequalitycomparer Using Linq
Threadstatic V.S. Threadlocal<T>: Is Generic Better Than Attribute