Reputation: 1
I have something like this :
class powerup {
public static int cooldown = 1;
}
class freeze : powerup {
//some unrelated code
}
class burn : powerup {
//unrelated
}
and i'd like to have a different value for the cooldown of the freeze and burn powerups, and in a static way since i can't instantiate them where i set the cooldown, and it also makes more sense to have them static since they are unique. So i feel like i'm needing to override the cooldown with "new" , but it doesnt feel right. Is there any solution i'm not aware of ? Thanks in advance
Upvotes: 0
Views: 208
Reputation: 660058
There is no combination of overridability and staticness in C#; those are in a sense opposites.
The better technique would be to make instances; those instances could be singletons if that makes sense. I'd be inclined to do something like:
abstract class Powerup
{
public virtual int Cooldown => 1
}
sealed class Freeze : Powerup
{
}
sealed class Burn : Powerup
{
public override int Cooldown => 2;
}
But a technique I particularly like when these are singletons is:
abstract class Powerup
{
private Powerup() {} // Prevent instantiation
public virtual int Cooldown => 1
public static readonly Powerup Freeze = new FreezePower();
private sealed class FreezePower : Powerup
{
}
public static readonly Powerup Burn = new BurnPower();
private sealed class BurnPower : Powerup
{
public override int Cooldown => 2;
}
}
Now look at the use site:
Console.WriteLine(Powerup.Freeze.Cooldown); // 2
That looks really nice at the use site I think.
Upvotes: 3
Reputation: 4219
You can use the new modifier to hide the parent property on child classes, such as:
class powerup
{
public static int cooldown = 1;
}
class freeze : powerup
{
public new static int cooldown = 3;
//some unrelated code
}
class burn : powerup
{
public new static int cooldown = 2;
//unrelated
}
This provides the following results:
Console.WriteLine($"powerup: {powerup.cooldown}");
Console.WriteLine($"freeze: {freeze.cooldown}");
Console.WriteLine($"burn: {burn.cooldown}");
Upvotes: 2
Reputation: 3500
I believe you are wanting to update the cooldown value of all instances of a specific powerup. In that case, I would use something like this:
interface IPowerup {
int Cooldown { get; set; }
}
class Freeze : IPowerup {
private static int _cooldown;
public int Cooldown { get { return _cooldown } set { _cooldown = value; }
public Freeze() { Cooldown = 1; }
}
class Burn : IPowerup {
private static int _cooldown;
public int Cooldown { get { return _cooldown } set { _cooldown = value; }
public Burn() { Cooldown = 2; }
}
So now, if you set the cooldown for one powerup, you set the value for all.
You can also do away with the constructors and instantiate the powerups and set the cooldown period like this:
var burnPowerup = new Burn { Cooldown = 2 };
Upvotes: 0