Click here to Skip to main content
15,889,216 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
Hello. I got a tricky question that probably comes from a really horrible code, but I'll ask it anyway.

I have a father class and few classes that inherit from him. Each one of the classes should have a const "name" attribute (can't make it static because I need to use it in a "switch" statement and it doesn't allow me to use non-const) so I can't make an inheritable constant and must create a new one in all of the children classes. What should I do in that situation to fix my code to have an inheritable const?
Posted
Comments
[no name] 20-Jul-14 11:16am    
Being that this makes no sense at all to me, why can't you use typeof to get the type of the class?

What are you talking about?
C#
    public void Demo()
        {
        MyDerived md = new MyDerived();
        int i = 9;
        switch (i)
            {
            case MyBase.AttributeOne:
                Console.WriteLine("ONE");
                break;
            case MyBase.AttributeTwo:
                Console.WriteLine("TWO");
                break;
            }
        }
    }

public abstract class MyBase
    {
    public const int AttributeOne = 1;
    public const int AttributeTwo = 2;
    }
public class MyDerived : MyBase
    {
    }

Works for me...
 
Share this answer
 
Using "switch" statement on something which plays the role of the type classifier ("Name", in your case) is a typical and a very bad violation of OOP. Also, it looks like you really need some read-only member, not exactly a formal constant.

To get an idea, consider, for example, this:
C#
abstract class Base {
    internal abstract string Name { get; } //read-only
}

class Derived : Base {
    internal override string Name { get { return "Some Name"; } } //read-only
}

class AnotherDerived : Base {
    internal override string Name { get { return "Some Other Name"; } } //read-only
}

//...

Base instance = new Derived();
string name = instance.Name; // will return "Some Name";


—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900