Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Access array without null exception

Tags:

c#

try-catch

I have to set these variables through with the QueryString array:

UtmSource = HttpContext.Current.Request.QueryString["utm_source"];
UtmMedium = HttpContext.Current.Request.QueryString["utm_medium"];
UtmCreative = HttpContext.Current.Request.QueryString["utm_creative"];
UtmCampaign = HttpContext.Current.Request.QueryString["utm_campaign"];
UtmTerm = HttpContext.Current.Request.QueryString["utm_term"];
UtmContent = HttpContext.Current.Request.QueryString["utm_content"];
Tag1 = HttpContext.Current.Request.QueryString["utm_source"];
Tag2 = HttpContext.Current.Request.QueryString["m"];

Some keys in the query string might throw null exception.

I don't want to wrap each var in try catch and I don't want to wrap all with try catch because if the first one fails, the entire will be null/avoided.

How can I safely access these variables?

like image 827
SexyMF Avatar asked Jan 18 '26 09:01

SexyMF


1 Answers

I would use the null-coalescing operator to make it nice and simple

UtmSource = Request.QueryString["utm_source"] ?? "DefaultValue"

You can read more about the operator at MSDN.

like image 127
Stefan Avatar answered Jan 20 '26 21:01

Stefan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!