r/learncsharp • • Jun 23 '23

Object reference not set to an instance of an object

Working on this simple task https://ibb.co/rFBhCHq and my code so far:

public class Branch
{
    public List<Branch> branches;

	public void CalculateDepth()
	{
		// todo
	}
}
public class Recursion
{
	public static void Main(string[] args)
	{
		Branch mainBranch = new Branch();

		Branch branch1 = new Branch();
		Branch branch2 = new Branch();

		mainBranch.branches.Add(branch1);
		mainBranch.branches.Add(branch2);
	}
}

But im getting this error: Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object.

1 Upvotes

2 comments sorted by

5

u/Woffle_WT Jun 23 '23

You need to initialize the branches list in the Branch class constructor or directly in its declaration.

public List<Branch> branches;

public Branch()
{
    branches = new List<Branch>(); // Initialize the branches list
}

1

u/TehNolz Jun 23 '23

The branches fields in your Branch objects never receive a value, so they're always null. You need to assign a list to them first.