How to force a derived class to include certain properties with default value

mikedev picture mikedev · Jan 28, 2010 · Viewed 8.2k times · Source

I have a class structure for a role playing game which looks like this...

public abstract class Item
{
   public abstract string Name { get; set; }
}

public abstract class Armor : Item
{
   public override string Name { get; set; }
}

public class Helmet : Armor
{
   public override string Name { get; set; }
}

Basically, I am trying to force every derived type to include a "Name" property. Is this the best way to do it? I know I can remove "abstract" from Item.Name and then remove the overriden "Name" properties in Armor and Helmet. If I do that the code looks a little cleaner but I might forget to set the base.Name in these derived classes.

Could someone help show me the best way to do this?

EDIT: Sorry, let me clarify my question a little more. I want to make sure of 2 things. 1) Name property exists in all derived classes 2) Name property is not null or empty

I basically want to force any class that derives from Item (and is not abstract) to have a value for Name.

Answer

David Hall picture David Hall · Jan 28, 2010

It sounds like you are worried about initialising properties?

but I might forget to set the base.Name in these derived classes.

One way the you can force the Name property to be set is to include this setter in your base class constructor like so:

public class MyBaseClass
{
    private string _name;

    public MyBaseClass(string name)
    {
        _name = name;
    }
}

Then everything that derives from MyBaseClass must satisfy that constructor:

public class MyDerivedClass
{
    public MyDerivedClass(string name) : base(name)
    {

    }
}

Then you can also make the property either:

  • abstract to ensure that it exists in each derived class with its own implementation
  • virtual to provide a base implementation and all it to be overridden.

I'm not going to venture whether the above is good design, but it would work to ensure that all derived classes have a valid name property when instantiated.

Another approach, as other answers suggest, is to implement a virtual property that throws an exception in its base implementation.