Skip to content

Instantly share code, notes, and snippets.

@dejanstojanovic
Created February 3, 2015 04:32
Show Gist options
  • Save dejanstojanovic/22ec356ec42f1d7e385d to your computer and use it in GitHub Desktop.
Save dejanstojanovic/22ec356ec42f1d7e385d to your computer and use it in GitHub Desktop.
Convert string value to C# strong type
/// <summary>
/// Converting the string value to T type
/// </summary>
/// <typeparam name="T">Type to convert string value to</typeparam>
/// <param name="value">String value to be converted to type T</param>
/// <returns>Returns converted string value to type T</returns>
public static T ConvertTo<T>(this string value) where T : IConvertible
{
var typeCode = default(T).GetTypeCode();
switch (typeCode)
{
case TypeCode.Boolean:
Boolean boolVal = default(Boolean);
Boolean.TryParse(value, out boolVal);
return (T)Convert.ChangeType(boolVal, typeCode);
case TypeCode.Byte:
Byte ByteVal = default(Byte);
Byte.TryParse(value, out ByteVal);
return (T)Convert.ChangeType(ByteVal, typeCode);
case TypeCode.Char:
Char CharVal = default(Char);
Char.TryParse(value, out CharVal);
return (T)Convert.ChangeType(CharVal, typeCode);
case TypeCode.DateTime:
DateTime DatetTimeVal = default(DateTime);
DateTime.TryParse(value, out DatetTimeVal);
return (T)Convert.ChangeType(DatetTimeVal, typeCode);
case TypeCode.Decimal:
Decimal DecimalVal = default(Decimal);
Decimal.TryParse(value, out DecimalVal);
return (T)Convert.ChangeType(DecimalVal, typeCode);
case TypeCode.Double:
Double DoubleVal = default(Double);
Double.TryParse(value, out DoubleVal);
return (T)Convert.ChangeType(DoubleVal, typeCode);
case TypeCode.SByte:
SByte SByteVal = default(SByte);
SByte.TryParse(value, out SByteVal);
return (T)Convert.ChangeType(SByteVal, typeCode);
case TypeCode.Single:
Single SingleVal = default(Single);
Single.TryParse(value, out SingleVal);
return (T)Convert.ChangeType(SingleVal, typeCode);
case TypeCode.UInt16:
UInt16 UInt16Val = default(UInt16);
UInt16.TryParse(value, out UInt16Val);
return (T)Convert.ChangeType(UInt16Val, typeCode);
case TypeCode.UInt32:
UInt32 UInt32Val = default(UInt16);
UInt32.TryParse(value, out UInt32Val);
return (T)Convert.ChangeType(UInt32Val, typeCode);
case TypeCode.UInt64:
UInt64 UInt64Val = default(UInt16);
UInt64.TryParse(value, out UInt64Val);
return (T)Convert.ChangeType(UInt64Val, typeCode);
case TypeCode.Int16:
Int16 int16Val = default(Int16);
Int16.TryParse(value, out int16Val);
return (T)Convert.ChangeType(int16Val, typeCode);
case TypeCode.Int32:
Int32 int32Val = 0;
Int32.TryParse(value, out int32Val);
return (T)Convert.ChangeType(int32Val, typeCode);
case TypeCode.Int64:
Int64 Int64Val = 0;
Int64.TryParse(value, out Int64Val);
return (T)Convert.ChangeType(Int64Val, typeCode);
}
return default(T);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment