Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Lack of Static Inheritance - What Should I Do?

Alright, so as you probably know, static inheritance is impossible in C#. I understand that, however I'm stuck with the development of my program.

I will try to make it as simple as possible. Lets say our code needs to manage objects that are presenting aircrafts in some airport. The requirements are as follows:

  • There are members and methods that are shared for all aircrafts

  • There are many types of aircrafts, each type may have its own extra methods and members. There can be many instances for each aircraft type.

  • Every aircraft type must have a friendly name for this type, and more details about this type. For example a class named F16 will have a static member FriendlyName with the value of "Lockheed Martin F-16 Fighting Falcon".

  • Other programmers should be able to add more aircrafts, although they must be enforced to create the same static details about the types of the aircrafts.

  • In some GUI, there should be a way to let the user see the list of available types (with the details such as FriendlyName) and add or remove instances of the aircrafts, saved, lets say, to some XML file.

So, basically, if I could enforce inherited classes to implement static members and methods, I would enforce the aircraft types to have static members such as FriendlyName. Sadly I cannot do that.

So, what would be the best design for this scenario?

like image 227
yellowblood Avatar asked Apr 09 '10 00:04

yellowblood


1 Answers

One answer is to decorate each class with attributes (metadata):

[Description("Lockheed Martin F-16 Fighting Falcon")]
public class F16 : Aircraft
{
    // ...
}

This is using the DescriptionAttribute already in System.ComponentModel.

You can get the metadata like this:

Type t = typeof(F16);
DescriptionAttribute attr = (DescriptionAttribute)Attribute.GetCustomAttribute(t,
    typeof(DescriptionAttribute));
string description = (attr != null) ? attr.Description : t.Name;

This will get you the description text from a reference to the F16 class.

like image 194
Aaronaught Avatar answered Sep 21 '22 21:09

Aaronaught