0

Below is Parent & Child class.

public class ParentController : ApiController
{
   public ICustomer customer { get; set;}
   public ICustUtil util { get; set;}

}


public class ChildController : ParentController
{
    //no issue here
    public string Get()
    {
       customer = util.GetCustomers();
     }

}

If I make the parent class properties as protected & try to use them, I get Object NULL reference Exception

public class ParentController : ApiController
{
   protected ICustomer customer { get; set;}
   protected ICustUtil util { get; set;}

}


public class ChildController : ParentController
{
    //Object Null reference exception at run time here
    public string Get(){
    customer = util.GetCustomers();}

}

I am trying to understand how does it make difference updating public to protected access specifier.

Please note:-

  • I am using Castle Windsor DI container

Please ignore naming convention for now.

Kgn-web
  • 7,047
  • 24
  • 95
  • 161
  • @Kgn-web: No, that code really won't compile. You need something like `public class ParentController : ApiController`. Then your `ChildController` code won't compile either, as you have a non-declaration directly in the class declaration. Please provide a [mcve]. (I'd also strongly advise you to learn about .NET naming conventions.) – Jon Skeet Mar 01 '17 at 08:33
  • @JonSkeet, My typo mistake. I sincerly apologize for it – Kgn-web Mar 01 '17 at 08:35
  • The reason for your exception not-regarding your compiler-errors is probably that you never instantiate your `utils`-property within your `ChildController`-class. – MakePeaceGreatAgain Mar 01 '17 at 08:35
  • @HimBromBeere, as I metioned that I am using DI Nulll reference issue arise only when making the members as protected – Kgn-web Mar 01 '17 at 08:37
  • @JonSkeet, I have corrected my post,can you please share your thoughts now?? Thanks – Kgn-web Mar 01 '17 at 08:43
  • "Please ignore naming convention for now." Why not just *fix it* instead? Stack Overflow is intended to be a repository of high-quality questions and answers - you should put effort into making your question as high quality as posisble. It doesn't help that you haven't shown us *how* you're using Castle Windsor... we still have no way of reproducing the problem. Presumably nothing is setting `ICustUtil` to a non-null value, but we don't know what you've done to try to set that up. – Jon Skeet Mar 01 '17 at 08:51

1 Answers1

2

I am guessing you are instantiating instances of these classes via an IoC container like AutoFac, and you are using setter injection. Otherwise I can't see how the first example would ever work, since you never initialize util.

When a member is protected, an IoC container can't initialize it. Only public members can be accessed by code outside the class itself.

John Wu
  • 50,556
  • 8
  • 44
  • 80