-4

When I am trying to give value to a variable which is (should be) an object of another class DataContext through constructor it's always a null and I get a NullReferenceException. When I am trying to this by set accessor everything works fine.

public class DataRepository
{
    private DataContext data;
    private AnyFiller currentFiller;

    public AnyFiller CurrentFiller
    {
        get
        {
            return currentFiller;
        }
        set
        {
            this.currentFiller = value;
        }
    }

    public DataContext Data { get; set; }

    public DataRepository()
    {
        this.data = new DataContext();
    }

    public DataRepository(DataContext data)
    {
        this.data = data;
    }

neither one of constructors works fine, but as I said before, it's working when I am doing something like this:

        DataContext cont = new DataContext();
        DataRepository data = new DataRepository();
        data.Data = cont;

Could anybody tell me what am I doing wrong?

KonradL
  • 9
  • 3
  • 5
    public DataContext Data { get; set; } isnt using your private variable data, and so oen constructor uses the private "date" the other uses the public "Data".. – BugFinder Apr 03 '17 at 13:10
  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Drew Kennedy Apr 03 '17 at 13:13
  • So, the constructor should use accessor not a variable? Also; neither one of them works fine – KonradL Apr 03 '17 at 13:14

1 Answers1

2

In both your constructors, you are 'setting' your private field 'data'. But then you try to 'get' your property 'Data', which was implemented with the auto property shortcut.

You need to change your constructors to set the property 'Data' instead of the private field 'data'.

public DataRepository()
{
    this.Data = new DataContext();
}

public DataRepository(DataContext data)
{
    this.Data = data;
}

You can get rid of the private field 'data' because it is not related to your property 'Data' at all. If you want to explicitly relate your property Data to your private field 'data' you need to do so like this:

public DataContext Data { get { return data; } set { data = value; } } 
Daniel Marques
  • 683
  • 8
  • 17