-1

Below is my interface:

public interface IBaseService
{
    List<ExceptionPairs> Exceptions { get; set; }
}

Another interface is inheriting it:

public interface IClassStudentsService: IBaseService
{

}

I have implemented this interface in below class:

public class CSService : IClassStudentsService
{
    public List<ExceptionPairs> Exceptions
    {
        get;set;
    }
}

I have created a object of CSService and tried to access List 'Exceptions' but receiving error " Object reference not set to an instance of an object. "

Can you please guide what I need to do instantiate it ?

Robert Rouhani
  • 14,512
  • 6
  • 44
  • 59
haansi
  • 5,470
  • 21
  • 63
  • 91

2 Answers2

5

Exceptions is an auto-property for an object, and as such it has not been initialized before you are accessing it.

In the constructor, initialize the property with a new list:

public class CSService : IClassStudentsService
{
    public CSService() {
         Exceptions = new List<ExceptionPairs>();
    }

    public List<ExceptionPairs> Exceptions { get; set; }
}
Matt Tester
  • 4,663
  • 4
  • 29
  • 32
2

You need to add a constructor for your CSService class:

public CSService()
{
    Exceptions = new List<ExceptionPairs>();
}

In the constructor, you initialize the list.

Baldrick
  • 11,712
  • 2
  • 31
  • 35