1

I'm getting a System.TypeInitializationException exception on line 9 when running this code in which I attempt to fill a generic list in the class'static constuctor.

using System;
using System.Collections.Generic;

namespace ConsoleApplication5_static_constructor {
    public static class DataRepository {
        public static List<DefinedField> Tables;
        static DataRepository() {
            Console.WriteLine("static DataRepository constructor fired");
            Tables.Add(new DefinedField("ID"));  **//this is line 9**
        }
    }

    public class DefinedField {
        string _tableName;
        public DefinedField(string tableName) {
        _tableName = tableName;
    }

        public string TableName {
            get { return _tableName; }
            set { _tableName = value; }
        }

    }
}

Call code:

using System.Collections.Generic;

namespace ConsoleApplication5_static_constructor {
    class Program {
        static void Main(string[] args) {
            List<DefinedField> x = DataRepository.Tables;
        }
    }
}

What exactly is causing the error and how do i solve it, please?

Edit: Also there is an inner exception of the type NullReferenceException Is a static constructor not capable of initializing new objects?

kitty
  • 67
  • 8
  • Generally when you get exceptions you dont understand have a look at the InnerException. This would have been a NullReferenceException which would tell you the cause. – CathalMF Apr 15 '16 at 08:15
  • Thanks, I'll keep this in mind for the next time. I'm glad you guys helped me so quickly. Actually it would've taken me a while to figure this out, probably because I'm more used to write python scripts – kitty Apr 15 '16 at 08:21
  • @CathalMF Generally yes, but not when the exception happens in a static constructor. – Maarten Apr 15 '16 at 08:44
  • @Maarten I recreated this myself and it has a NullRefererenceException in the InnerException – CathalMF Apr 15 '16 at 08:45

1 Answers1

4

Your static property Tables is not initialized. It is showing as an TypeInitializationException because the exception is firing in the static constructor. So the exception happens when the type DataRepository is being initialized.

The solution is to set it to an empty list.

public static List<DefinedField> Tables = new List<DefinedField>();
Maarten
  • 22,527
  • 3
  • 47
  • 68