Unnie Unnie - 2 months ago 8
C# Question

C# : make derived object conditionally share same base object

I have a base class with is inherited by multiple derived classes. I am initializing some properties of base class in constructor. Is there any way i can make the base class property being shared by my derived objects rather than creating the same property values for each derived class object. This is really important because some of the base class property values are generated by services and sharing this can improve performance.
Below is somewhat a simple blueprint of what i am trying to say:

public class ClassA
{
//i dont want to use static here as it will be shared for multiple codes
protected string country { get; set; }
public ClassA(string code)
{
country = CallsomeService(code);
}
}

public class ClassB : ClassA
{
public ClassB(string code) : base(code)
{
//blah blah
}

public void DomeSomethingWithCountry()
{
Console.WriteLine($"doing this with {country} in classB");
}
}

public class ClassC : ClassA
{
public ClassC(string code) : base(code)
{
//blah blah
}

public void DomeSomethingWithCountry()
{
Console.WriteLine($"doing soemthing else with {country} in classC");
}
}


Now making objects like below

public void test()
{
//call service for this
var classb=new ClassB("1");
//dont call service for this
var classc=new ClassC("1");
classb.DomeSomethingWithCountry();
classc.DomeSomethingWithCountry();
//call service for this as code is different
var classb1=new ClassB("2");
}

Answer

You could store the result of having made the call statically, rather than the value itself.

public class ClassA
{
    static Dictionary<string,string> codeToCountryLookup
         = new Dictionary<string,string>();
    protected string country { get; set; }
    public ClassA(string code)
    {
       if(!codeToCountryLookup.ContainsKey(code))
            codeToCountryLookup.Add(code,CallsomeService(code));
       country = codeToCountryLookup[code];
    }
}

This is not in any way threadsafe, but should give you somewhere to start.