0

Is it possible to access the fields and or constants of an abstract class? Suppose I have the code:

public abstract class A
{
    private int A;
    private int B;

    public const int months = 12;

    public int AProp
    {
        get{ return A; }
        set{ A = value; }
    }

    public abstract void DoSomething();
}

Is it possible to retrieve the fields and the constant by reflection? If yes, can you please suggest how? And, is there a better way to do this?

Ira Baxter
  • 93,541
  • 22
  • 172
  • 341
PBrenek
  • 561
  • 1
  • 8
  • 24
  • When you ask, is there a better way than reflection, that depends on what you are trying to do with the abstract class. Could you elaborate a little? – BradleyDotNET Mar 13 '14 at 21:48
  • @LordTakkera I simply meant if there is a way to do it without using reflection. Sorry for the poor wording. – PBrenek Mar 13 '14 at 21:51
  • @PBrenek if you can access that variables, then what would be the point of **private** modifier ? – Selman Genç Mar 13 '14 at 21:52
  • You can access these from derived classes if they are protected, and the outside if they are public (the private ones are trickier of course). So yes, you can do it without reflection. A use case of "how" you want to access it would enable me to tell you if that scenario would work or not. – BradleyDotNET Mar 13 '14 at 21:52
  • Are you talking about retrieving them from a specific instance of the class (of a subclass in our case)? Or do you want to do something like Abstract.months? – Benesh Mar 13 '14 at 21:55
  • @LordTakkera I am interested particularly in the private ones. You imply that it can be done. As to a scenario, I am not sure how to access them so I am not able to give you one. – PBrenek Mar 13 '14 at 21:56
  • I am interested in retrieving them. – PBrenek Mar 13 '14 at 21:57
  • Have you looked at this answer?http://stackoverflow.com/questions/6961781/reflecting-a-private-field-from-a-base-class – BradleyDotNET Mar 13 '14 at 22:04
  • I have tried something similar:Type type = typeof(IndicatorBase); PropertyInfo[] propInfo = type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly); foreach(PropertyInfo prop in propInfo) { Print("name prop = "+prop.Name); } – PBrenek Mar 13 '14 at 22:10

1 Answers1

0

If you want the fields to be accessible from the DoSomething method but not be visible to external classes, the simplest choice would be to make your fields protected. That way they are only accessible to subclasses, and you can almost think of protected as "private for abstract classes".

The differences however is of course, that you can implement the abstract class from other assemblies. To avoid this you can make the class internal.

faester
  • 14,886
  • 5
  • 45
  • 56