A Coder
A Coder

Reputation: 3046

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?

Upvotes: 0

Views: 1960

Answers (4)

Kamil Budziewski
Kamil Budziewski

Reputation: 23097

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.

Upvotes: 0

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73482

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

Upvotes: 1

Lee
Lee

Reputation: 144136

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);

Upvotes: 4

King King
King King

Reputation: 63337

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

Upvotes: 5

Related Questions