Convert a String to any Type as Nullable
By Peter Bromberg
Often when working with objects like the DataRow it is necessary to check for DbNull.Value. Here is a generic method that will accept a string representing any type, along with the type desired, and it will convert to the required value or null.
/// <summary>
/// Convert a string to any type as nullable
/// </summary>
/// <typeparam name="T">Type</typeparam>
/// <param name="valueAsString">string value</param>
/// <returns>Nullable instance of coverted value</returns>
public static T? GetValueOrNull<T>( string valueAsString )
where T : struct
{
if (string.IsNullOrEmpty(valueAsString))
return null;
return (T)Convert.ChangeType(valueAsString, typeof(T));
}
Usage:
cd.DocumentID = GetValueOrNull<long>(row["i_document_id"].ToString());
You can also easily turn this into an extension method on the String type:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyProject
{
public static class MyProjectExtensions
{
/// <summary>
/// Convert a string to any type as nullable
/// </summary>
/// <typeparam name="T">Type</typeparam>
/// <param name="valueAsString">string value</param>
/// <returns>Nullable instance of coverted value</returns>
public static T? GetValueOrNull<T>( this string valueAsString )
where T : struct
{
if (string.IsNullOrEmpty(valueAsString))
return null;
return (T)Convert.ChangeType(valueAsString, typeof(T));
}
}
}
usage:
var cd = new Thing();
cd.Amount = row["amount"].ToString().GetValueOrNull<decimal>();
An alternative that avoids the need to call ToString() on the object to process is
to use type Object:
public static T? GetValueOrNull<T>(this object candidate) where T : struct
{
if (candidate == DBNull.Value)
return null;
return (T)Convert.ChangeType(candidate, typeof(T));
}
The above would be especially useful when processing DataRow Items,
which are always type Object.
Convert a String to any Type as Nullable (1383 Views)