Convert String to Nullable Type (Int, Double, etc...)

Convert string to nullable type (int, double, etc...)

Another thing to keep in mind is that the string itself might be null.

public static Nullable<T> ToNullable<T>(this string s) where T: struct
{
Nullable<T> result = new Nullable<T>();
try
{
if (!string.IsNullOrEmpty(s) && s.Trim().Length > 0)
{
TypeConverter conv = TypeDescriptor.GetConverter(typeof(T));
result = (T)conv.ConvertFrom(s);
}
}
catch { }
return result;
}

Creating a generic method for converting string to nullable numbers

There's an identical question here (in C#): Convert string to nullable type (int, double, etc...)

Public Function ConvertString(Of T As Structure)(ByVal value As String) As System.Nullable(Of T)
Try
Return DirectCast(Convert.ChangeType(value, GetType(T)), T)
Catch
Return Nothing
End Try
End Function

How to parse a string into a nullable int

int.TryParse is probably a tad easier:

public static int? ToNullableInt(this string s)
{
int i;
if (int.TryParse(s, out i)) return i;
return null;
}

Edit @Glenn int.TryParse is "built into the framework". It and int.Parse are the way to parse strings to ints.

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);
}

convert int to nullable int?

That To code seems to be you trying to construct a Constant of nullable type when given a value of non-nullable type but that is not at all the right way to go about this. The way you're trying to do this indicates that you have a misunderstanding about how boxed value types work.

That error message indicates that you are constructing a binary operator expression tree node which has as its operands an expression node of nullable int type and an expression node of int type. That's not legal; they have to be both nullable int. What you should be doing is wrapping the non-nullable int expression tree node in a Convert expression tree node which converts it to a nullable int, and then pass that to the binary operator expression tree node constructor.

That is, this is wrong:

var someIntExpr = Expression.Constant(123, typeof(int));
var someNubIntExpr = Expression.Constant(null, typeof(int?));
var badEq = Expression.Equal(someIntExpr, someNubIntExpr);

This is right:

var goodEq = Expression.Equal(Expression.Convert(someIntExpr, typeof(int?)),  someNubIntExpr);

So why is what you're doing wrong?

You have a method To<T> which returns a T. It correctly takes in an int and returns the equivalent int?. So then what? You pass that to Expression.Constant, which boxes the nullable int into a boxed int, and then makes a constant out of that. You believe that there is such a thing as a boxed nullable value type, but there is not! A nullable value type boxes either to a null reference or to a boxed non-nullable value type.

So you could also solve your problem by not doing any of this crazy stuff in the first place. If you have a boxed int in hand, and you need a constant expression tree node of nullable type, just provide the type.

Expression.Constant(someBoxedIntValue, typeof(int?))

Done. So: wrapping up, you have two solutions:

  • If you have a boxed int in hand, pass it and the nullable value type you want to the Constant factory, or
  • if you have an expression node of type int in hand then use the Convert expression node factory, and pass it and the desired type to that.

Both will give you back an expression node of the correct type to be compared to another nullable int.

convert string null value to int

Try:

 public static int? ToNullableInt32(string s)
{
int i;
return (Int32.TryParse(s, out i)) ? i : null;
}

EDIT: I noticed your comment to your original question about it only working with DBNull values. In that case, try adding...

cmd.Parameters.AddWithValue("@type_id", ToNullableInt32(p.type_id) ?? DBNull.Value)

...in addition to the ToNullableInt32 method update.

Converting `Type` to `NullableType`

Please use the following function:

public Type GetNullableTypeFrom(Type type)
{
if (!type.IsValueType || type.IsGenericType)
return type;

var nullableType = typeof(Nullable<>).MakeGenericType(type);

return nullableType;
}

It will convert your type into a nullable one if the source type isn't, otherwise just leave it as it is.

if (allowNulls)
{
type = GetNullableTypeFrom(type);
}


Related Topics



Leave a reply



Submit