-3
public class Blah
{
    public bool Whatever { get; set; }
    public string WhatYouJustSaid { get; set; }
}

public interface IBlah
{
    Blah BlahValues { get; set; }
}

class Class1:IBlah
{
    public Blah BlahValues { get; set; }
}

And then for example:

   Class1 c1 = new Class1();
   c1.BlahValues.WhatYouJustSaid = "nothing";
    c1.BlahValues.Whatever = false;

So how should I change my code that BlahValues doesn't get null?

Bohn
  • 24,195
  • 54
  • 155
  • 240
  • This has nothing to do with the fact that you're using an interface. You have a property that you you never initialized. Of course it'll be null. You have to assign a value to BlahValues – Jonesopolis Apr 21 '16 at 19:25

2 Answers2

1

You have to initialize the BlahValues. Using an object initializer, this can be done as below:

Class1 c1 = new Class1()
{
   BlahValues = new Blah() 
};

As you create the c1 object, the BlahValues get it's default value, which is null. Hence, when you try to assign a value to WhatYouJustSaid and Whatever you get a null reference exception.

Christos
  • 50,311
  • 8
  • 62
  • 97
  • Can you take a look at this question I had please ? In that question I was using Ninject and NSubstitute and getting a null exception crash which first I thought it is becuase I am new to both of those but then I recreated the way I am using interfaces in this question and got the same null exception. So maybe you can help with my actual question here too ? http://stackoverflow.com/questions/36777185/using-nsubstitute-and-ninject-to-return-a-value – Bohn Apr 21 '16 at 19:29
0

use it like this inside the constructor of Class1

public  Class1()
{
    this.BlahValues = new Blah() 
}
rashfmnb
  • 7,839
  • 4
  • 29
  • 41