dotnet ??= and array? - getting basic understanding
Working with ??= is really good to reduce some boiler plate code such as the ones below
// using ??=
List<string>? arrayList3 = null;
var result5 = arrayList3 ??= new List<string>();
// replacing tedious if else statement :)
if (arrayList3 == null)
{
var result6 = new List<string> { "test" };
}
And allow us to quickly, checks for null and apply default value
string? dummyString = null;
arrayList.Add(dummyString ??= "default");
To work with array?[], it seems to be confusing to me. I wasn't really sure if it is checking if the array itself is null or array index value is null. It is checking if the array is null. And of course, whether it will throw exception if i tries to access an invalid index.
Additional details are shown here:
// working with array
var arrayList = new List<string>();
arrayList.Add("test");
//var result = arrayList?[2]; // exception
var result2 = arrayList?[0]; // result2 = test
// safer way to work with array?
var result3 = (arrayList.Count > 4) ? arrayList[4] : null;
// using method extension
var result4 = arrayList.GetOrNull(4); // result 4 is null but won't throw exception
Console.WriteLine("Done");
public static class ListExtensions
{
public static T? GetOrNull<T>(this IList<T> list, int index) where T : class
{
return (index >= 0 && index < list.Count) ? list[index] : null;
}
}
Comments