Darf
Darf

Reputation: 2585

How to set a struct value T from Type

I'm using the extension from Joel's string-to-nullable-type answer here:

public static Nullable<T> ToNullable<T>(this string s) where T: struct
{
    Nullable<T> result = new Nullable<T>();
    try
    {
        if (!string.IsNullOrEmpty(s) && s.Trim().Length > 0)
        {
            TypeConverter conv = TypeDescriptor.GetConverter(typeof(T));
            result = (T)conv.ConvertFrom(s);
        }
    }
    catch { } 
    return result;
}

And in my code, I've got the data from a Type. Is there a way to cast or use that extension using Type?

UPDATE 1:

var values = from p in xdoc.Descendents("Answers")
         select r.Attribute("Value").Value.ToNullable<Type.GetType(r.DataType)>()

r.DaraType is a data string.

Upvotes: 0

Views: 114

Answers (1)

Coding Flow
Coding Flow

Reputation: 21881

No you can't specify a generic type argument to be the result of a method call that returns a Type object.

i.e. this is invalid ToNullable<Type.GetType(r.DataType)>()

The type needs to be evaluated at compile time and if your syntax was valid the compiler could not tell what the type was in result of your linq query.

Upvotes: 3

Related Questions