Reputation: 2401
I'm having problems accessing the attributes of a property defined in an abstract class when property is marked internal. Here is some example code:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class CustomAttribute : Attribute
{
}
public abstract class BaseModel
{
[CustomAttribute]
protected DateTimeOffset GenerationTime { get { return DateTimeOffset.Now; } }
[CustomAttribute]
public abstract string FirstName { get; } // Attribute found in .NET 3.5
[CustomAttribute]
internal abstract string LastName { get; } // Attribute not found in .NET 3.5
}
public class ConcreteModel : BaseModel
{
public override string FirstName { get { return "Edsger"; } }
internal override string LastName { get { return "Dijkstra"; } }
[CustomAttribute]
internal string MiddleName { get { return "Wybe"; } }
}
class Program
{
static void Main(string[] args)
{
ConcreteModel model = new ConcreteModel();
var props = model.GetType().GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).ToList();
List<PropertyInfo> propsFound = new List<PropertyInfo>(), propsNotFound = new List<PropertyInfo>();
for (int i = props.Count - 1; i >= 0; i--)
{
var att = Attribute.GetCustomAttribute(props[i], typeof(CustomAttribute), true) as CustomAttribute;
if (att != null)
propsFound.Add(props[i]);
else
propsNotFound.Add(props[i]);
}
Console.WriteLine("Found:");
foreach (var prop in propsFound)
{
Console.WriteLine(prop.Name + ": " + prop.GetValue(model, null));
}
Console.WriteLine(Environment.NewLine + "Not Found:");
foreach (var prop in propsNotFound)
{
Console.WriteLine(prop.Name + ": " + prop.GetValue(model, null));
}
Console.ReadKey();
}
}
When I run this program on .NET 3.5, the attribute on the LastName
property is not found and the output is the following:
When I run this program on .NET 4.0, the all the attributes are found correctly. Here is the output:
Is this just simply a bug that existed in .NET 3.5 and was fixed in .NET 4.0? Or is there some other subtlety that I'm missing that will allow me to access the attributes of internal abstract properties?
Note: This also seems to be true for virtual properties only when they are overridden in the concrete class.
Upvotes: 1
Views: 517
Reputation: 31596
I reproduced what you saw and took a look at Microsoft Connect. There was no reported issue (by the public) which listed an issue for GetCustomAttribute failure with internal. But that doesn't mean it wasn't found and fixed internally.
You can post this as a connect issue (link) and see if there is a hot fix releated to .Net 3.5.
Upvotes: 1