Aside from the property/setter argument I can't see any logical reason for this in the code you have provided.
However, if you want to perform extra operations on the object before setting it to null it makes sense:
if (MyBills != null)
{
MyBills.Dispose();
MyBills = null;
}
Or perform some other operation like logging a result.
But these two examples are both outside of the example code you have provided.
Because people seem to be questioning the use case for my first example, here's one. This will prevent multiple calls to Dispose
causing an ObjectDisposedException
.
public class MyClass : IDisposable
{
private SomeDisposableObject _disposableObject;
//Some code
public void Dispose()
{
if (_disposableObject != null)
{
_disposableObject.Dispose();
_disposableObject = null;
}
}
}
I have performed some timings and found the following results:
valueClass with null check = 1361
nullClass with null check = 1173
valueClass with no null check = 1208
nullClass with no null check = 1148
As you can see without the null check it is slightly quicker but not enough for any significant optimisation. Also I performed these timings from the compiler in debug mode with optimisations turned off so they are not 100% accurate/relevant.
However, when I ran in release mode, with optimisations enabled outside of the compiler the results were so close together it was even more negligible to check or not.
And the test code:
using System;
namespace NullCheckTest
{
class Program
{
const int iterations = 10000000;
static void Main(string[] args)
{
MyClass valueClass = new MyClass() { Value = 10 };
MyClass nullClass = null;
Console.WriteLine($"valueClass with null check = {TestNullCheck(valueClass)}");
Console.WriteLine($"nullClass with null check = {TestNullCheck(nullClass)}");
Console.WriteLine($"valueClass with no null check = {TestNoNullCheck(valueClass)}");
Console.WriteLine($"nullClass with no null check = {TestNoNullCheck(nullClass)}");
Console.ReadLine();
}
static long TestNullCheck(MyClass myClass)
{
MyClass initial = myClass;
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
for (int i = 0; i < iterations; ++i)
{
sw.Start();
if (myClass != null)
{
myClass = null;
}
sw.Stop();
myClass = initial;
}
return sw.ElapsedMilliseconds;
}
static long TestNoNullCheck(MyClass myClass)
{
MyClass initial = myClass;
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
for (int i = 0; i < iterations; ++i)
{
sw.Start();
myClass = null;
sw.Stop();
myClass = initial;
}
return sw.ElapsedMilliseconds;
}
}
public class MyClass
{
public int Value { get; set; }
}
}