Home Null pointer exceptions and warnings
Post
Cancel

Null pointer exceptions and warnings

Simple code

I am developer so let’s start with following C# code:

1
2
3
4
5
6
7
8
9
10
11
12
    public static void Main()
    {
        var sampleList = GetSamples();
        if (sampleList.FirstOrDefault().StartsWith("I"))
        {
            Console.WriteLine("First element starts with I");
        }
        else
        {
            Console.WriteLine("First element doesn't start with I");
        }
    } It compile without any warnings, which is quite cool, But will it work without problems? Of course it depends on `GetSamples` function. But it should, isn't it?

Full implementation

So let’s extend above code to full implementation:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
    static readonly Random Random = new Random();
    static List<string> GetSamples()
    {
        if (Random.Next(100) > 2)
        {
            return new List<string>{"I"};
        }
        return new List<string>();
    }
    public static void Main()
    {
        var sampleList = GetSamples();
        if (sampleList.FirstOrDefault().StartsWith("I"))
        {
            Console.WriteLine("First element starts with I");
        }
        else
        {
            Console.WriteLine("First element doesn't start with I");
        }
    }

Now it starts to look tricky and dangerous. But again you will don’t have any warning in Visual Studio.

Resharper to the rescue

If you use R# you will see following warning:

Using Alt+Entershortcut generate simple fix:

1
2
3
4
5
6
7
8
9
var firstOrDefault = sampleList.FirstOrDefault();
if (firstOrDefault != null && firstOrDefault.StartsWith("I"))
{
   Console.WriteLine("First element starts with I");
}
else
{
   Console.WriteLine("First element doesn't start with I");
}

And we are safe now :)

##… but it doesn’t show everything But imagine that instead of FirstOrDefault() the developer used First(), so the above if will be following:

1
if (sampleList.First().StartsWith("I"))

In above case it won’t be any warning even in Resharper :(

Sum up

This post is licensed under CC BY 4.0 by the author.