Search code examples
c#listenumspropertiesclass-properties

Runtime error when trying to add item to list property in a class in C#


I have a class with a property that is a List of enum values to be filled in runtime (I'm using a List instead of an array because I don't know beforehand how many items there will be).

I declared the property like this:

public class Entity 
{
    // ...
    public List<FooEnum> FooList { get; set; }
    // ... 
}

where FooEnum has the following structure:

public enum FooEnum
{

    [Description( "Foo: " )]
    Foo = 1,

    [Description( "Boo: " )]
    Boo = 3,

    [Description( "Loo: " )]
    Loo,

    //...
}

To add items to the list I added the following method to the Entity class:

public void SetFoos( string packet )
{
    VectorSize = short.Parse( ExtractValue( packet, "ListSize: " ) );

    for( int i = 0, start = packetIndexOf( "ListSize" ); i < VectorSize; i++ )
    {
        string reducedPacket = packet.Substring( start );
        string currentFoo = ExtractValue( packet, "--------------\r\n" );

        foreach( FooEnum foo in FooEnum.GetValues( typeof( FooEnum ) ) )
        {
            if( foo.Description().StartsWith( currentFoo ) ) { FooList.Add(foo); break; }
        }
    }
}

I haven't implemented the start update logic yet because I wanted to test an example where VectorSize was 1, but when running the program I got a runtime error:

System.NullReferenceException : Object reference undefined for object instance

I tried to declare the list as public List<FooEnum> FooList = new List<FooEnum>();, but immediately I got a warning telling me that

Field "Entity.FooList" is never atributted and will always have a default null value

so I went back to using a getter and a setter.

I tried to find some examples of List properties in C# and based on them I tried changing my declaration to

public class Entity 
{
    // ...
    private List<FooEnum> fooList;
    public List<FooEnum> FooList 
    {
        get { return fooList; } 
        set { fooList = value; } 
    }
    // ... 
}

but I got the same runtime error.

What am I missing? Is it not possible to use a list of Enums as a class property?


Solution

  • Add a constructor to your Entity class and initialize the FooList or foolist like below

    public class Entity 
    {
        public List<FooEnum> FooList { get; set; }
    
        // ctor 
        public Entity()
        {
            FooList = new List<FooEnum>();
        }
    }