Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there a sort of isset() on .NET/C#?

Tags:

c#

.net

I need to check if there is a param on the uri request.

So I need to check if that param is set. Is there a function on .NET/C#?

like image 234
markzzz Avatar asked Nov 11 '11 13:11

markzzz


People also ask

What is an isset () function?

The isset() function checks whether a variable is set, which means that it has to be declared and is not NULL. This function returns true if the variable exists and is not NULL, otherwise it returns false.

How do I use isset?

The isset() function is an inbuilt function in PHP which checks whether a variable is set and is not NULL. This function also checks if a declared variable, array or array key has null value, if it does, isset() returns false, it returns true in all other possible cases.

What is the return type of Isset in PHP?

The isset() returns a boolean value. It will return true if the parameter passed is declared and is not set NULL. In the case, where over one parameter is passed (they can be of different data types), the isset() will return true only if all the passed variables are not equal to NULL and their values exist.


2 Answers

An unset value will be null or empty:

value = Request["param"];
if (String.IsNullOrEmpty(value))
{
    // param is not set
}

If the param name is in the query string but the value is not, it will be empty. If the name is not in the query string, the value will be null. For example.

&param1=&param2=value 
// Request["param1"] is String.Empty
// Request["param3"] is null
like image 154
jrummell Avatar answered Sep 28 '22 19:09

jrummell


Yes, you can use HttpUtility.ParseQueryString() utility method which returns NameValueCollection and then cust call Get():

bool contains = HttpUtility.ParseQueryString(uri.Query)
                           .Get("ParameterName") != null;

Get() method

Returns A String that contains a comma-separated list of the values associated with the specified key from the NameValueCollection, if found; otherwise, null

EDIT:

If you have an instance of the HttpRequest then just use built in indexer like below:

bool contains = Request["ParamName"] != null;
like image 38
sll Avatar answered Sep 28 '22 20:09

sll