0

I have a Conversion class like this:

public class Conversion
{
    public memorySource MSource { get; set; }
    public Rule[] Rules { get; set; }
    public Conversion(XElement xElement)
    {
       // I use Rules property here 
       // From Rules property and xElement parameter i initialize MSource Property
    }

    public Conversion(ExcelPackage)
    {
       // Also i use Rules property here 
       // From Rules property and xElement parameter i initialize MSource Property
    }
}

When I want to construct an instance of the Conversion class, I do this:

Conversion cvr = new Conversion(xElement) { Rules = rules };

Then I get this error:

Object reference not set to an instance of an object

I know that construction of object begins before initializing of properties, but is there a way to do inverse?

I can use Rules property as parameter of constructor but it is not suitable for performance because I have several constructors.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
YouneL
  • 8,152
  • 2
  • 28
  • 50
  • you have to initialize rules in the constructor or add another constructor that takes Rules as you said. there is no other way – Selman Genç Dec 04 '14 at 10:54

1 Answers1

2

Yes, simply pass the value as parameter in the constructor. It's the only way:

Conversion cvr = new Conversion(rules, package);

Where the constructor is:

public Conversion(Rule[] rules, ExcelPackage package)
{
   this.Rules = rules;

   ...
}

You can default the rules parameter for your other constructor, so you don't have to duplicate code:

public Conversion(ExcelPackage package) : this(new Rule[] { ... }, package)
{
   ...
}
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325