What is wrong with the Dictionary in a class property?

Why is this code not working?

public class A   
{
   public Dictionary<int, string> dic { get; set; }   
}

class Program   
{
    public static void Main()
    {
        A a = new A();
        a.dic.Add(1, "a");
    }   
}

Error: Correction System.NullReferenceException was unhandled Message = Object reference not installed in the object instance.

+3
source share
4 answers

You did not initialize the property, so the value a.dicis null (the default for any reference type).

You will need something like:

a.dic = new Dictionary<int, string>();

... or you can initialize it in the constructor.

On the other hand, it is rarely possible to have such direct access to the inner workings of a class - here you have no encapsulation.

+7
source

- . null. " " ; , .

+2
    public class A
    { public Dictionary dic;

A()

{

dic = new Dictionary();
}

    }

    class Program
    { public static void Main() { A a = new A(); a.dic.Add(1, "a");

    }   

    }
0

A :

public class A
{
    public Dictionary<int, string> dic { get; set; }

    public A()
    {
        dic = new Dictionary<int, string>();
    }
}

The key point is that you need to initialize the "dic" property before you can use it.

0
source

Source: https://habr.com/ru/post/1773314/


All Articles