-2

Trying to assign a value to the _cat.CatType.

I was wondering how to do this without getting a null reference error?

using System;

public class Program
{
    private CatClass _cat;
    public void Main()
    {
        _cat.CatType = CatType.Active;

        Console.WriteLine(_cat.CatType.ToString());
    }

    public enum CatType
    {
        New,
        Active,
        Inactive
    }

    public class CatClass
    {
        public CatType CatType
        {
            get;
            set;
        }
    }
}

Ideally I want to assign it something like this _cat.CatType = CatType.Active

3 Answers3

2

You need to initialise it with the new keyword

Used to create objects and invoke constructors

public void Main()
{
    _cat = new CatClass();
    _cat.CatType = CatType.Active;

    Console.WriteLine(_cat.CatType.ToString());
}
TheGeneral
  • 79,002
  • 9
  • 103
  • 141
0

You need to create an instance of the class.

private CatClass _cat = new CatClass;
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
0

Instantiate _cat with the new keyword first:

_cat = new CatClass
{
    CatType = CatType.Active
};
RoadRunner
  • 25,803
  • 6
  • 42
  • 75