I have the following class:
public class DataSource
{
[DisplayName("Value")]
public string Value { get; set; }
[DisplayName("Title")]
public string Title { get; set; }
}
The following code to retrieve:
public DataSource Get(string ds)
{
if (ds != null && ds == "0000")
return GetDataSources().Single(s => s.Value == ds);
return null;
}
If the value of ds is null or “0000” then I need the following to
return null but it gives an exception:
var dsa = _dataSource.GetTitle(ds).Title;
Is there something I could do to make the “.Title” return null rather than an exception if ds is null or “0000”?
The short answer would be a simple “no”. What you are looking for is the “null safe dereference operator”, which does not exist in C#.
There are a full things you can do, but to be honest I suspect the best option is simply: check the value before the member-access.
Other options:
GetTitle(this DataSource source) {...}) that checks thesourceappropriately; extension methods can be called onnullinstances, soGetTitle(ds).GetTitle()will work even ifnullis returned