Sitemap

Using Default values for Nullable Variables is a Bad Practice — .NET Core

2 min readNov 29, 2023

--

All nullable variables, or class members (excluding collections) should have their value set to NULL unless a value is available. Setting a default value to a nullable is a bad practice.

What do I mean? well, see the code blocks below:

// Below is the wrong way to consume a value

Decimal myValue = GetDummyValue() ?? 0m;
DoSomthing(myValue);

// Below is the correct way to comsume a value

Decimal? myValue = GetDummyValue();

if (myValue.HasValue)
{
DoSomthing(myValue);
}

Reason: a NULL is itself a value to indicate that the required value is not available to consume. Setting a default value muddies the water and creates confusion.

Why so? so here is my story …

Just recently while refactoring an internal project, an API started producing strange results.

There was not much changed during refactoring, just a few lines of code where a default DateTime type value was being set to a nullable variable.

Get Yaz’s stories in your inbox

Join Medium for free to get updates from this writer.

the code initially looked something like below:

public ActionResult<double> GetUserActivity()
{
DateTime expiration = _userContext?.GetSessionExpiration() ?? DateTime.MinValue;
if(expiration == DateTime.MinValue) { return this.Ok(999.9); }
double remaining = (expiration - DateTime.Now).TotalSeconds;
return this.Ok(remaining);
}

After the refactor, the code was changed to something like the below:

public ActionResult<double> GetUserActivity()
{
double expirationSeconds = null;
var expiration = this._userContext?.GetSessionExpiration();

if (expiration != null)
{
var expirationSeconds = (expiration- DateTime.Now).TotalSeconds;
}

return this.Ok(expirationSeconds);
}

It was mind-boggling since the API was returning insanely high value for expirationSeconds which was unexpected.

So, I started examining the code in the bottom layers, and behold I found the reason. Below was the line that was causing this problem:

public DateTime GetSessionExpiration(string SessionRefId)
{
return _userContextService.GetUserSessionExpiration(SessionRefId) ?? DateTime.MinValue;
}

In the above code, the programmer was setting a default value of DateTime type to DateTime.MinValue which is ‘0001–01–01’ and at the time of consumption of this value at a higher level, another null check was applied, and a default value was assigned there as well.

So, I corrected it as below:

public DateTime? GetSessionExpiration(string SessionRefId)
{
return _userContextService.GetUserSessionExpiration(SessionRefId);
}

and the issue was gone!!

🔔 Follow me for more content like this! 🔔

If you find this content helpful and want to show your support, you can buy me a coffee ☕.

--

--

Yaz
Yaz

Written by Yaz

Feel free to reach for any professional help at callmeyaz01@gmail.com