Question

I have a generic function where the T could be anything from int to Dictionary string,string or List int if i use T tmpOb = default(T); and return tmpOb later for int returns 0 which is fine but for a List int it returns null but it would be realy cool if i could get a empty List int instead.

i could do something like

public static T ConvertAndValidate<T>(string bla)
{
    T tmpOb = default(T);
    if (typeof(T) == typeof(List<int>))
    {
        tmpOb = new List<int>();
    }
    else if(typeof(T) == typeof(List<string>))
    {
        tmpOb = new List<string>();
    }

    //Do other generic stuff that could overwrite the value of tmpOb 

    return tmpOb;
}

is their any real generic way to achieve that? Something like

public static T ConvertAndValidate<T>(string bla)
{
    T tmpOb = default(T);
    if (typeof(T) == typeof(List<x>))
    {
        tmpOb = new List<x>();
    }

    //Do other generic stuff that could overwrite the value of tmpOb 
    return tmpOb;
}
Was it helpful?

Solution

Yes there is, with a generic constraint:

public static T ConvertAndValidate<T>(string bla)
    where T : new()
{
    T t = new T();
}

OTHER TIPS

I am not completely with your requirement... But the possible solution to assign a empty list or empty object or for that matter any value type, the below line can be used

Activator.CreateInstance<T>();

I hope this should serve your purpose.

I am also not certain about your needs, but you could change your method to:

    private static T ConvertAndValidate<T>(string bla)
    {
        T ret = default(T);
        if (typeof(System.Collections.IList).IsAssignableFrom(typeof(T)))
        {
            if (typeof(T).GetGenericArguments().Length > 0)
            {
                ret = (T)Activator.CreateInstance(typeof(T));
            }
        }
        return ret;
    }

This will check if it is an IList and if it contains generic arguments. Thats it...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top