0

I have created class called ExcelMethods contains:

public class ExcelMethods
{
 public string DestinationPath { get; set; }    
 public List<MyUsers> LoadExcelFile()
 {
  //My code
 }

Now into my MainViewModel I want to set DestinationPath and call LoadExcelFile():

public class MainViewModel
{
  public ExcelMethods _em;
  public MainViewModel()
  {            
   _em.SourcePath = @"\\abc.test\\folderA";
  }

  private void LoadExcel_Executed(object obj)
  {
   _em.LoadExcelFile();
  }      
}

But I'm getting error:

System.NullReferenceException: 'Object reference not set to an instance of an object.'
4est
  • 3,010
  • 6
  • 41
  • 63
  • Where `_em` instantiated ? which line you got that exception ? – Aria Feb 27 '19 at 07:51
  • This is a common duplicate (already answered) question. In your MainViewModel class you never call `_em = new ExcelMethods();` – Cleptus Feb 27 '19 at 07:52
  • `_em` is null. You need to initialize it by doing `_em = new ExcelMethods();` before doing `_em.SourcePath = @"\\abc.test\\folderA";` – Chetan Feb 27 '19 at 07:55
  • You never assign a value to `_em`. And your profgram can´t automatically create an instance of the class and assign it to your variable. That´s why you get that error. – MakePeaceGreatAgain Feb 27 '19 at 07:56

1 Answers1

1

Change public ExcelMethods _em; to public ExcelMethods _em = new ExcelMethods()

The reason you get your error is because you never actually instanciate your object _em but only declare it. A Null reference is a common error I would recommend you to read up on exceptions and actually learn what causes them.

Niklas7
  • 173
  • 8