views:

220

answers:

2

Lets say I have two classes:

class A
{
   [SortOrder(3)]
   public string Name { get; set; }
}

class B : A
{
   [SortBefore(*****)]
   public string Age { get; set; }
}

Note the stars in the property attribute in the second class. Would it somehow (using expressions I guess) be possible to specify A.Name in the SortBefore attribute? Note that I'm not after the value of Name in an instance of A but the PropertyInfo for the property Name in A so that I, when working with the PropertyInfo for Age in B, can retrieve the SortOrder value from it's superclass.

+2  A: 

You can't, I'm afraid. It may be possible in IL - I'm not sure - but you can't do it in C#.

The closest you could come would be:

[SortBefore(typeof(A), "Name")]

and get the attribute to find the property at execution time. And yes, this is very brittle - if you do this, I'd add a unit test which finds all the attributes in an assembly and checks they're all valid.

Jon Skeet
+1  A: 

Even the C# typeof operator is implemented by the compiler as a ldtoken followed by a call to Type.GetTypeFromHandle(). The PropertyInfo is a particularly interesting case because the ldtoken IL instruction can't take a Property metadata token as an argument, and there is no RuntimePropertyHandle type. However, the getter and/or setter methods can be obtained in IL via (this is not valid IL but shows the instructions). Unfortunately there is no direct way in C# to produce this code with the level of type safety that the typeof() operator provides.

ldtoken <method>
call MethodBase.GetMethodFromHandle

The answer to this earlier question shows how to get the PropertyInfo from the MethodInfo.

Jon's answer is correct about the solution you'll probably have to use.

280Z28