Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inherit a static property with a unique value for each subclass?

Tags:

c#

inheritance

I have a series of objects, lets call them buildings, that each share certain properties that are static for that building, but different for each building, such as price. I assumed that the best way to implement this was to create an abstract superclass with the shared price attribute and set the values in each subclass, but I cannot figure out how to get this to work. Here is an example of something I have tried:

using System;
public abstract class Buildings
{
   internal static int price;
   internal static int turnsToMake;
}
using System;
public class Walls : Buildings
{
    public Walls()
    {
        price = 200;
        turnsToMake = 5;
    }
}

This works fine for construction, but if I want to check the price before creating it (to check if the player has enough money) then it just returns a null value. I'm sure that it is is a super simple fix, but I can't figure it out. Any help?

like image 293
Garrett Avatar asked Dec 09 '22 17:12

Garrett


2 Answers

There is a "patchy" yet simple solution that's worth to consider. If you define your base class as a Generic class, and in deriving classes set T as the class itself, It will work.

This happens because .NET statically defines a new type for each new definition.

For example:

class Base<T>
{
    public static int Counter { get; set; }

    public Base()
    {
    }
}

class DerivedA : Base<DerivedA>
{
    public DerivedA()
    {
    }
}

class DerivedB : Base<DerivedB>
{
    public DerivedB()
    {
    }
}

class Program
{
    static void Main(string[] args)
    {

        DerivedA.Counter = 4;
        DerivedB.Counter = 7;

        Console.WriteLine(DerivedA.Counter.ToString()); // Prints 4
        Console.WriteLine(DerivedB.Counter.ToString()); // Prints 7

        Console.ReadLine();
    }
}
like image 137
Uri Abramson Avatar answered Dec 11 '22 09:12

Uri Abramson


Don't use static. Static says that all instances of Building have the same value. A derived class will not inherit its own copy of the statics; but would always modify the base class statics. In your design there would only be one value for price and turnsToMake.

This should work for you:

public abstract class Buildings
{
  internal int price;
  internal int turnsToMake;
}

However, most people don't like using fields these days and prefer properties.

public abstract class Buildings
{
  internal int Price { get; set; }
  internal int TurnsToMake { get; set; }
}
like image 21
Richard Schneider Avatar answered Dec 11 '22 07:12

Richard Schneider