Saeid
Saeid

Reputation: 13582

Convert Nullable<Boolean> to 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

}

So this method always rise an exception in return line:

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

I don't understand where is the problem I don't use Boolean I use Boolean?

this is my call line:

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

So what is your idea about it?

Upvotes: 4

Views: 2447

Answers (2)

user743382
user743382

Reputation:

I don't understand where is the problem I don't use Boolean I use Boolean?

Yes, but you're unknowingly converting it to Boolean before ChangeType sees it.

The first parameter has type Object. When a nullable value type, in this case bool?, is converted to object, you either get null, or an instance of the non-nullable type. So by the time ChangeType sees it, it's no longer a nullable boolean.

The real problem is that Converter just doesn't support nullable types. At best, you could special case, if the type is T?, check if the parameter is null or an empty string, if so, return null, otherwise, convert to T. Or not use Converter where it's not the best way to go.

Upvotes: 3

Eli Arbel
Eli Arbel

Reputation: 22739

You can use

return (T)(object)istrue;

I would not use this kind of code at all though. Simply create a method that specifically parses each data type (e.g. bool? GetBooleanParameter(string name)). You're not gaining anything with the generics here and only making the code more cumbersome.

Upvotes: 8

Related Questions