Search code examples
c#return-valuedefault-valuereturn-type

In c#, is it a good practice to return default literal?


Recently, I saw some are writing code to return default literal for nullable primitive type, is there a real benefit for it?

To make it simple,

int? TestDefault(int input)
{
    if (input > 10)
    {
        return input;
    }
    else
    {
        return default;
    }
}

In the code above, it return default (it is null for type int?)

It looks good at the 1st glance.

But the problem is that when the return type of the function is changed from int? to int, it will return 0, which may be unintentional (sometimes, the magic number may be a negative number instead of 0) and easily gets ignored by the one who changes it (because there is no compile error and 0 seems making sense) especially when the one is changing a lot of long and complex methods.

Indeed, for default literals, they are 0/false/null. All of them are of less letters than default. What is the reason we use the default literal here? By specifying 0/false/null explicitly, it makes clearer that what is the value it is expecting.


Solution

  • Why would someone be changing the function signature? I recommend being explicit with types you know such as int, keeping it 0 so it's always 0 on default, no matter whether the int is wrapped in a Nullable struct. However, default becomes more useful when dealing with generics, where default(T) would return null for class generics and the default fielded struct for struct generics. Essentially, my opinion is that it's not a good practice for things like this :)