views:

71

answers:

2

Given the class':

public abstract class AbstractEntity
{
    public virtual Guid Id { get; private set; }
}

public class Entity
{
    public virtual Guid Id { get; private set; }
}

And a PropertyInfo for the property 'Id'.

When calling the method:

PropertyInfo.GetAccessors()

It returns both the get-method and the set-method when the class is not abstract (Entity), but only the get-method when the class is abstract (AbstractEntity).

Why is this? And is there another way to get the set-method from a property with a private set?

A: 

In an abstract class, you can't instantiate it. Barring reflection, there is nothing that can call the private setter. In reflection, you still have to instantiate the class (not including static items) to access properties call methods etc, and this can't be done in an abstract class. Being able to access it wouldn't grant you anything, and in fact nothing can access it to use it.

Kevin
Well, that argument would go for all private members, but that doesnt explain why this is any different for abstracts. ITs true i cant instantiate the class directly, but that doesnt keep me from wanting to describe it via reflection?I accept not being able to set it, due to security issues, but why not be able to read wether is there or not?
Lars Udengaard
Well, no, because in other private members, when the object is instantiated they exist. With the private abstract member, that can't ever happen.
Kevin
+2  A: 

If you want to get the MethodInfo for the set, you can. That doesn't mean you can actually use it, as Kevin point in his answer.

Type t = typeof(AbstractEntity);
MethodInfo[] mi = t.GetProperty("Id").GetAccessors(true);
anchandra
A bake to differ, as i point out that doesnt work. Only for the non-abstract class.
Lars Udengaard
The code above will return 2 methodInfo objects, one for the get and one for the set. What do you want to do with them after that? I tested this code with a ConsoleApplication
anchandra
You are right, my error was elsewhere. Thanks for pointing out! :-)
Lars Udengaard