-2

What is wrong with this code?

public partial class MainForm : Form
 {
        private Dictionary<String , PropertyInfo[]> types;  
        public MainForm()
        {
            //OpenAccountStruct is in the scope
            types.Add("OpenAccount", new OpenAccountStruct().GetType().GetProperties());
        }
} 

Why am I getting NullReferenceException?

gsharp
  • 26,016
  • 21
  • 83
  • 126
SexyMF
  • 9,829
  • 31
  • 94
  • 187
  • Put types = new Dictionary(); on the first line of your method. – Mike Chaliy Sep 22 '11 at 07:18
  • 1
    Basic debugging would have taught you that `types` is the null reference here, and so your question has very little, if anything, to do with Reflection. – Damien_The_Unbeliever Sep 22 '11 at 07:19
  • Almost all cases of `NullReferenceException` are the same. Please see "[What is a NullReferenceException in .NET?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)" for some hints. – John Saunders May 15 '14 at 19:38

4 Answers4

4

You didn't make an instance of types (your Dictionary).

try

types = new Dictionary<String , PropertyInfo[]>();
gsharp
  • 26,016
  • 21
  • 83
  • 126
1

The types variable is not initialized. Use types = new Dictionary<String , PropertyInfo[]>();

Johann Blais
  • 9,249
  • 6
  • 44
  • 63
0
 private Dictionary<String , PropertyInfo[]> types = 
                        new Dictionary<String , PropertyInfo[]>();
Rami Alshareef
  • 6,787
  • 11
  • 44
  • 74
0

Obviously, your types field is not initialized,

 public partial class MainForm : Form
 {
        private Dictionary<String , PropertyInfo[]> types = new Dictionary<String , PropertyInfo[]>();
        public MainForm()
        {
            //OpenAccountStruct is in the scope
            types.Add("OpenAccount", new OpenAccountStruct().GetType().GetProperties());
        }
} 
ojlovecd
  • 4,532
  • 1
  • 17
  • 22