-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
  • 27,557
  • 22
  • 88
  • 134
SexyMF
  • 10,657
  • 33
  • 102
  • 206
  • 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
  • 27,557
  • 22
  • 88
  • 134
1

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

Johann Blais
  • 9,389
  • 6
  • 45
  • 65
0
 private Dictionary<String , PropertyInfo[]> types = 
                        new Dictionary<String , PropertyInfo[]>();
Rami Alshareef
  • 7,015
  • 12
  • 47
  • 75
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,812
  • 1
  • 20
  • 22