Programming in C#: Common Error Guide

Here’s your guide to some of the most common errors and what you can do to find them. If you find yourself having trouble still, I suggest giving a look at my debugging tutorial to find your problem!

Don’t forget you can always try googling your errors too, more than likely someone has had this issue and tried asking for help.

Null Reference Exception

This is one of the most common errors you’ll see. A quick review, there are value types and reference types. Value types are things like ints, floats, etc. They cannot be null, they always have some kind of value. Reference types reference some location in memory, and so if you haven’t created a spot for it (by using new for example to create an instance) then it has no value, and is null.

So when you have your variable it is probably a reference type (classes are reference types, structs are value types). Somewhere you haven’t given your reference type variable a value, so it is still null.

You have to fill that reference by setting the variable to another variable, or function that returns the value. If it’s a custom class, or a list, you have to create a new instance, using new ClassName() or new List<int>() for example.

Index Out of Range Exception

Another very common error when dealing with collections, types like lists or arrays.

These types all have sizes, like a list starts with a size of 0 and increases whenever you use .Add, and arrays you set their size when you make them by doing new ArrayType[size]. So when you try to get a value that isn’t in the collection size, you’ll get this error. If the size is 0, then any index you try to use with collection[0 - anything] will give you this error. Any negative numbers too.

One issue you might see is if trying to use something collection[collection.Length], because collections start with a 0 index, so the length of the collection may be 4, but the indices are 0, 1, 2, and 3. So [4] doesn’t exist.

0 comments on “Programming in C#: Common Error GuideAdd yours →

Leave a Reply

Your email address will not be published. Required fields are marked *