I don’t have a clue how to summarize my question .. but I need a little help with some class inheritance and static variables.

This is a very dumbed down example just to simplify my question. This is very difficult to explain so hopefully I pull it off.

So, say I have a class Car. I create other classes Prius and Bronco, which inherit Car.

Every instance of Prius will have some configurable options such as color, but it also has some information about it that will never change, such as Brand and Weight, regardless of the instance. Same with all other car model classes which inherit Car.

I can do this:

public class Car { public string color { get { return color; } set { color = value; } } public Car() { } } public class Prius : Car { public static readonly string brand = "Toyota"; public static readonly int weight = 3000; public Prius() { } public Prius(string color) { this.color = color; } } public class Bronco : Car { public static readonly string brand = "Ford"; public static readonly int weight = 5800; public Bronco() { } public Bronco(string color) { this.color = color; } } 

And then elsewhere in my code quickly retrieve the information I need without having to instantiate a new instance. Great.

string broncoBrand = Bronco.brand; 

And I can still grab the make by referencing the type. Great.

Bronco myBronco = new Bronco("Hot Pink"); string myBroncoColor = myBronco.color; string myBroncoBrand = Bronco.brand; 

I want to be able to retrieve Brand and Weight without having to instantiate a new Prius or Bronco. But I want the Weight and Brand properties to be an essential attribute of any Car, not manually duplicated inside every single class which inherits it. For one thing, I don't like having to copy/paste the brand/weight declarations on every class. Another thing is, at some point I'm going to want to be able to search for all classes which inherit from car and grab certain static properties from them.

Is there any good way to pull this off? Hopefully that all made sense. Thanks in advance for any help.

by SocksForBreakfast via /r/csharp

Leave a Reply