ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

ConvertTo

Método de Extensión para convertir un String a cualquier tipo de Dato

Source

public static TValue ConvertTo<TValue>(this string text)
{
  TValue res = default(TValue);
  System.ComponentModel.TypeConverter tc = System.ComponentModel.TypeDescriptor.GetConverter(typeof(TValue));
  if (tc.CanConvertFrom(text.GetType()))
    res = (TValue)tc.ConvertFrom(text);
  else
  {
    tc = System.ComponentModel.TypeDescriptor.GetConverter(text.GetType());
    if (tc.CanConvertTo(typeof(TValue)))
      res = (TValue)tc.ConvertTo(text, typeof(TValue));
    else
      throw new NotSupportedException();
  }
  return res;
}

Example

var texto = "123123";
var res = texto.ConvertTo<int>();
res++;

Author: Jorge García Casalett

Submitted on: 14 jun. 2014

Language: C#

Type: System.String

Views: 5838