简体   繁体   中英

No implicit conversion between int and string

When i try to execute this belo code i'm getting that error.

//Code:

 int Value = Convert.ToInt32(Request.QueryString["Value"] == null ? 0 : Request.QueryString["Value"]);

So i need to pass the value '0' if the QueryString value is null.

How can i solve this?

int Value = Convert.ToInt32(Request.QueryString["Value"] ?? "0");

You could pass the string "0" but a better way would be:

int Value = Request.QueryString["Value"] == null ? 0 : Convert.ToInt32(Request.QueryString["Value"]);

and you could also factor out the lookup:

string str = Request.QueryString["Value"];
int value = str == null ? 0 : Convert.ToInt32(str);

Try this

int Value = Convert.ToInt32(Request.QueryString["Value"] == null ? "0" : Request.QueryString["Value"]);

Or take the advantage of ?? operator

int Value = Convert.ToInt32(Request.QueryString["Value"] ?? "0");

Your false and true statement in Ternary operator should be of same type or should be implicitly convertible to another.

Either the type of first_expression and second_expression must be the same, or an implicit conversion must exist from one type to the other.

Taken from msdn

Try this:

int i;
int.TryParse(Request.QueryString["Value"], out i);

if parsing will fail i will have default value (0) without explicit assignment and checking if query string is null.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM