Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 212
  • Last Modified:

Retrieving a Constant from a polymorphic object

Hi all,

I have a number of classes, each inheriting from an interface, and each with a matching const (i.e. the name of the const is the same, the value is different).

If I'm viewing an instance of one of these classes polymorphically via the interface, is there an easy way to access it's constant value? I could obviously add methods to each base class to return the const, but I wondered if there was any other, perhaps better, way of doing it?

Thanks
Gerry
0
gamesmeister
Asked:
gamesmeister
1 Solution
 
AlexFMCommented:
Looking at clsss instance via interface, you don't see this constant. I think the best way is to add property to the interface and implement it in every class:

    interface ISample
    {
        void Foo();

        int Constant
        {
            get;
        }
    }

    class Class1 : ISample
    {
        void ISample.Foo()
        {
        }

        int ISample.Constant
        {
            get
            {
                return myConstant;
            }
        }

        const int myConstant = 1;
    };

    class Class2 : ISample
    {
        void ISample.Foo()
        {
        }


        int ISample.Constant
        {
            get
            {
                return myConstant;
            }
        }

        const int myConstant = 2;
    };

Client code:

            ISample s1 = new Class1();
            Console.WriteLine(s1.Constant.ToString());

            ISample s2 = new Class2();
            Console.WriteLine(s2.Constant.ToString());
0
 
gamesmeisterAuthor Commented:
Yeah, I figured that would be the best way, just wondered if I'd missed something.

Off to update 30+ subclasses...

Thanks Alex
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now