Search code examples
c#.netconstructorobject-initializers

Is there a way to initialize properties after construction of object?


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.


Solution

  • 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)
    {
       ...
    }