1

I have a generic class and I will derive about 20 different classes from it, each with a different datatype for the generic part. The Generic class will have a static field called ConfigField which identifies a field in a configuration file. I want to calculate this field by using a combination of the name of the derived class plus the name of the generic datatype that it wraps. So, example:

class BaseClass<T>
{
    static string ConfigField = string.format("{0}.{1}", ???, ???);
}
class DerivedInt: BaseClass<int>{}
class DerivedLong: BaseClass<long>{}
class DerivedString: BaseClass<string>{}
...
Console.WriteLn(DerivedString.ConfigField);

Which should result in "DerivedString.string" as result. Or is this not possible, since it's a static field, thus it exists only in the Generic base class? If so, any other solutions?

2
  • Do you need ConfigField to be static? Commented Jul 10, 2013 at 14:33
  • Yes. It's a global field used by all derived objects, thus only assigned once. Commented Jul 11, 2013 at 11:28

1 Answer 1

2

Try it:

class Program
{
    static void Main(string[] args)
    {
        Derived d = new Derived();

        Console.WriteLine(d.ConfigField); // Derived.String

        Console.ReadLine();
    }
}

abstract class Base<T>
{
    public string ConfigField { get; private set; }

    public Base()
    {
        ConfigField = string.Format("{0}.{1}", this.GetType().Name, this.GetType().BaseType.GenericTypeArguments[0].Name);
    }

}

class Derived : Base<string>
{

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.