Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting browser language and avoiding nullreference exception

Tags:

c#

I want to detect the browser language so I can switch languages when people connect to my website. But when a user hasnt filled in the language in the browsers options I always get a null value with

string browserlanguage = Request.UserLanguages[0]

How could I avoid the error "Object reference not set to an instance of an object."

like image 795
Sjemmie Avatar asked Apr 18 '11 11:04

Sjemmie


2 Answers

Check for Request.UserLanguages != null.

For instance:

var l = Request.UserLanguages;
string browserlanguage = l ?? l[0] : "en";
// fall back to en, or set to "" or null.

Edit: (re your comment) If the above fails, too, Request itself was null, which afaik is impossible (could you check Request != null to make sure?). Did you possibly have a null reference later in your code?

like image 165
mafu Avatar answered Oct 03 '22 08:10

mafu


string lang = (Request.UserLanguages ?? Enumerable.Empty<string>()).FirstOrDefault();
like image 35
abatishchev Avatar answered Oct 03 '22 08:10

abatishchev