string strUserId = null;
//Using if-else
if (Request["uid"] == null)
strUserId = string.Empty;
else
strUserId = Request["uid"];
//Using ternary operator
strUserId = Request["uid"] == null ? string.Empty : Request["uid"];
now lets use ?? operator
//Using ?? operator
strUserId = Request["uid"] ?? string.Empty;
Isn't it handy? What is does is, it check only for null, it it found left side null then return the value form right hand else it returns left hand site value itself. In our case if there is no uid in query string then will return empty string or else will return the value of uid from query string.
2 comments:
One more example
string sortExpression = (ViewState["SortExpression"] ?? String.Empty).ToString();
Thanks Imran this was really helpfull!
Post a Comment