Ahmad Kharbat

is there any way to check whether the variable is declared or available in the context before using it

in some case specially in asp.net with c# .. i need to use some Request variables.

like page.aspx variable=value

in this case with the page loads a variable called Request("variable") will be declared.

but if page.aspx has loaded normally without the variable=value thing, then the Request("variable") wouldn't be declared.

so i need to check if it exists first and according to it's value i would do some operation.. otherwise if it doesn't exist i would do something else.

some one suggest to do the following

if( variable != null)

{

do something...

}

else

{

// means it doesn't exist

}

which is not correct it gives a compilation error..




Re: Visual C# General Question about variables

Galin Iliev

Request's variables are hold as strings so you could check with string.IsNullOrEmpty

If you have integer value as parameter you could use this in following manner:

Code Snippet

int objectId = 0;

if (!string.IsNullOrEmpty(Request["Id"]))

{

objectId = int.Parse(Request["Id"]);

}

//use id here

OR

Code Snippet

if (!string.IsNullOrEmpty(Request["Id"]))

{

int objectId = int.Parse(Request["Id"]);

}

else

{

//work without ID

}

Hope this helps






Re: Visual C# General Question about variables

Ahmad Kharbat

thanks..

but i get a strange error when i use the following code

Code Snippet

if (! string.IsNullOrEmpty(Request.QueryString("RefId")))

{

referenceId = Convert.ToString(Request.QueryString("RefId"));

}

else

{

referenceId = GetUniqueKey(8, 25);

}

Error 3 'System.Web.HttpRequest.QueryString' is a 'property' but is used like a 'method'






Re: Visual C# General Question about variables

nielsvanvliet

Use:

Code Snippet

Request.QueryString["RefId"] // Ok

//Request.QueryString("RefId") // Not Correct


Methods are called with parenthesis.

Properties are called with nothing or square brakets (if there is one or more arguments).

QueryString is a collection (in this case), and the access is done with the indexer, which is a property (so, square braket).