Converting a Nullable <Boolean> to a Generic Type

Assume this method:

public T GetParameterValue<T>(string ParamName) {

if(typeof(T) == typeof(Boolean?) && Request.QueryString.AllKeys.Contains(ParamName)) {

                Boolean? istrue = null;

                if(Request.QueryString.GetValues(ParamName).FirstOrDefault() == "1")
                    istrue = true;
                else if(Request.QueryString.GetValues(ParamName).FirstOrDefault() == "0")
                    istrue = false;

                return (T)Convert.ChangeType(istrue, typeof(T));
            }

//Other types implementation

}

Thus, this method always raises an exception in the return line:

Invalid cast from 'System.Boolean' to 'System.Nullable`1[[System.Boolean, 
mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'.

I do not understand where the problem is, I do not use BooleanI useBoolean?

this is my call line:

Product.IsAllow= GetParameterValue<Boolean?>("IsAllow");

So what do you think of this?

+3
source share
2 answers

you can use

return (T)(object)istrue;

I would not use such code at all. Just create a method that specifically analyzes each data type (for example, bool? GetBooleanParameter(string name)). You get nothing from generics here and make the code more cumbersome.

+8
source

I do not understand where the problem is, I do not use BooleanI useBoolean?

Yes, but you unconsciously transform it in Booleanbefore you ChangeTypesee it.

Object. , bool?, Object, null, , . , , ChangeType , .

, Converter . , T?, , , , , T. Converter, .

+3

All Articles