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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With