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.
Right-click the control that you want to change, and then click Properties or press F4. Click the All tab in the property sheet, locate the Default Value property, and then enter your default value. Press CTRL+S to save your changes.
// As base-class pointer cannot access the derived class variable.
The DefaultValue property specifies text or an expression that's automatically entered in a control or field when a new record is created. For example, if you set the DefaultValue property for a text box control to =Now(), the control displays the current date and time.
- A derived class is a class that inherits the properties from its super class. For example, a Cat is a super class and Monx cat is a derived class which has all properties of a Cat and does not have a tail.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With