Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 998
Saeid Avatar asked Dec 21 '22 22:12

Saeid


1 Answers

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.

like image 104
Eli Arbel Avatar answered Jan 01 '23 09:01

Eli Arbel