Search code examples
c#.netsyntaxternary

What does the question mark followed by a period mean if it is next to a variable?


I am well aware of ternaries. Just wondering what on earth the question mark next to "l" in the following line of code:

public static string GetRegion()
        {
            var ipAddress = GetIPAddress();
            if (string.IsNullOrEmpty(ipAddress))
            {
                return "";
            }

            try
            {
                var ls = new LookupService(HttpContext.Current.Server.MapPath("~") + "/GeoIP/GeoIPCity.dat", LookupService.GEOIP_STANDARD);
                var l = ls.getLocation(ipAddress);

                return l?.region ?? "";
            }
            catch (Exception)
            {
                return "";
            }
        } 

what does l?.region ?? "" mean?


Solution

  • That's a mix of Null Propagation and Null Coalesce operator and thus l?.region ?? "" region will be evaluated only iff l is not null and if l.region evaluates to null then return a default value which is empty string