Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic structure for performing string conversion when data binding

Tags:

c#

generics

a little while ago i was reading an article about a series of class that were created that handled the conversion of strings into a generic type. Below is a mock class structure. Basically if you set the StringValue it will perform some conversion into type T

public class MyClass<T>
{
    public string StringValue {get;set;}
    public T Value {get;set;}
}

I cannot remember the article that i was reading, or the name of the class i was reading about. Is this already implemented in the framework? Or shall i create my own?

like image 916
Rohan West Avatar asked Nov 15 '22 12:11

Rohan West


1 Answers

Here is a little trick to convert strings into simple types (struct types) :

public T GetValueAs<T>(string sValue)
    where T : struct
{
    if (string.IsNullOrEmpty(sValue))
    {
        return default(T);
    }
    else
    {
        return (T)Convert.ChangeType(sValue, typeof(T));
    }
}
like image 152
Xaav Avatar answered Dec 28 '22 05:12

Xaav