HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

Returning null or what?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
nullreturningwhat

Problem

I have a C# function like below, and in the else block, the function must return something. I don't know whether returning null is a good practice or not.

public Nullable GetSprite(int x, int y)
{
    if (x <= xCount && y <= yCount)
    {
        return new Point(x * spriteHeight, y * spriteWidth);
    }
    else
    {
        return null;
    }
}

Solution

Yes, you could just write:

public Point GetSprite(int x, int y)
{
    if (x <= xCount && y <= xCount)
    {
        return new Point(x * spriteHeight, y * spriteWidth);
    }

    return null;
}


And write in the documentation it could return null if if (x <= xCount && y <= xCount)

So who use your code could just write

Point point = GetSprite(x, y);
if (point == null) { /* something went wrong, check variables! */ }
else { /* ok! go ahead! */ }


I found this syntax very useful, and could not lead to bugs if the programmer is alerted about the null.

And, anyway you don't need the else block since the return call will stop the function (except if there are any finally blocks, but it's not the case.).

Code Snippets

public Point GetSprite(int x, int y)
{
    if (x <= xCount && y <= xCount)
    {
        return new Point(x * spriteHeight, y * spriteWidth);
    }

    return null;
}
Point point = GetSprite(x, y);
if (point == null) { /* something went wrong, check variables! */ }
else { /* ok! go ahead! */ }

Context

StackExchange Code Review Q#43798, answer score: 14

Revisions (0)

No revisions yet.