C# TryCast function

Date: 2016-03-19

Update in 2022:

public static T GetFieldValue<T>(IDictionary<string, object> dict, string fieldName, T defaultValue = default)
{
	if (dict.TryGetValue(fieldName, out var value))
		return GetValueOrDefault(value, defaultValue);
	return defaultValue;
}

public static T ConvertValueOrDefault<T>(object value, T def = default)
{
	if (value == null) return def;
	if (value is T t) return t;
	if (typeof(T) == typeof(string)) {
		return (T)(object)$"{value}";
	}
	var basicType = Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T);
	try {
		return (T)Convert.ChangeType(value, basicType);
	} catch { } // ignore value conversion error
	return def;
}

When dealing with unknown values, e.g. user input or dynamic.
I wrote a small function:

public static T TryCast(T def, params object[] list)
{
	foreach (object obj in list)
	{
		if (obj == null)
			continue;

		//if (typeof(T) == typeof(string))
		//{
		//     if (String.IsNullOrWhiteSpace(obj.ToString()))
		//     {
		//         continue;
		//     }
		//}

		if (obj is T)
			return (T)obj;

		// for converting long to int etc.
		try
		{
			return (T)Convert.ChangeType(obj, typeof(T));
		}
		catch (Exception)
		{
			//Ignore
		}
	}
	return def;
}

The ‘skip empty strings’ is commented and may be used to fullfill your needs.

Usage example:

if (TryCast(false, table.Row["Enabled"])) {

}

A variation of this function, used to get the correct type from a key of the Session object:

public static T SessionGet(string key, T def)
{
	if (HttpContext.Current != null && HttpContext.Current.Session != null)
	{					 
		object obj = HttpContext.Current.Session[key];
		if (obj == null)
		{
			return def;
		}

		if (obj is T)
		{
			return (T)obj;
		}				
	}
	return def;
}

1080cookie-checkC# TryCast function