0

This is my class constructor and i'm initializing two other classes within it.

public class APiBLL
{
   private cParams _cParams  

   private customer _adapter;
   private company _adapterCompany;

   public APiInboundBLL(cParams cParams)
   {
       _cParams = cParams;

       _adapter = new customer(_cParams);
       _adapterCompany = new company(_cParams);
    }

}

Within Company class constructor additional property is added to cParams

public company(cParams cParams)
{
    cParams.schema = "client";
}

Issue => Newly assigned value(parameter property) should reflect only within _adapterCompany.

But it's reflecting(Mutating) on _adapter as well.

Emperor
  • 55
  • 1
  • 1
  • 5
  • 2
    seems `cParams` (horribly name by the way) is a reference-type. Changes to any of the references will be reflected by all other references - that's the entire point why we call them ReferenceTypes. Either make your class a `struct` (=valuetype), or create a new `cParams`-instance when you provide it to the constructor. – MakePeaceGreatAgain Nov 30 '22 at 10:57
  • https://stackoverflow.com/questions/5057267/what-is-the-difference-between-a-reference-type-and-value-type-in-c – Roman Ryzhiy Nov 30 '22 at 11:02
  • @MakePeaceGreatAgain I can't make it struct since these are autogenerated codes from our framework.. A solution maintaining current structure is preferred – Emperor Nov 30 '22 at 11:03
  • `company` class needs to maintain its own copy of `cParams` then. No way around that. OR it must create/use a composite that adds only this one parameter locally. – Fildor Nov 30 '22 at 11:16
  • ^^ btw. Why isn't `schema` a private property of `company`, then? – Fildor Nov 30 '22 at 11:20
  • Clone _cParams before you send it into company. `new company(Clone(_cParams));` You need to write the Clone function yourself. – Magnus Nov 30 '22 at 12:04

1 Answers1

1

You're reassinging the parameter in the company constructor. Instead create a local variable and assign it.

string company_schema;

public company(cParams cParams)
{
    company_schema = "client";
}
x-turbo
  • 19
  • 1
  • 4