Home > Software design >  Static child field in c#
Static child field in c#

Time:08-13

TLDR: Is the a way in c# to define a field that is just static within the child class and therefore dynamic in the parent class?

I have an abstract class - A - with many children - B1, B2, ... -. The parent class A has a field x. x is static within Bn, but not (necessarily) the same for two instances of different children of A, for example, B1 and B2.

I did come up with two non-optimal solutions:

I could define x dynamically in A, set x in the constructor of Bn and then create a dummy class-instance of Bn whenever I need to access the parameter, that works fine.

public abstract class A
{
    public A(...){...}
    public string x;
}
public class B:A
{
    public B(...) : base(...) 
    { 
        x = "This is B";
    }
}

// To access B.x
B dummy = new B(...);
dummy.x
// B.x would result in error, since x is not static

I could also define a static function in, for example, A that takes a type as input and returns the value of x for that given class Bn. Again, this would feel clumsy, plus A would need to be changed every time I code a new class Bm.

CodePudding user response:

Are you after an interface with a static method?

With

public interface IX { static string? X {get; } }

abstract class A : IX {}

class B1: A
{
    public static string? X => "Hey, I'm B1";
}

class B2: A
{
    public static string? X => "Hey, I'm B2";
}

the following

Console.WriteLine(B1.X);
Console.WriteLine(B2.X);

prints

Hey, I'm B1
Hey, I'm B2

BTW. In c# 11 interfaces are getting some new features (from interface (C# Reference)):

Beginning with C# 8.0, an interface may define a default implementation for members. It may also define static members in order to provide a single implementation for common functionality.

and

Beginning with C# 11, an interface may define static abstract or static virtual members to declare that an implementing type must provide the declared members. Typically, static virtual methods declare that an implementation must define a set of overloaded operators.

  • Related