Consider following codes:
[AttributeUsage(AttributeTargets.Class)]
public sealed class SampleAttribute : Attribute
{
public String Name {get;set};
public SampleAttribute(String testName)
{
Name = testName;
}
}
[SampleAttribute("A")]
[SampleAttribute("B")]
public class Test
{
}
var attributes = typeof(Test).GetCustomAttributes<SampleAttribute>();
Unfortunately, the method "GetCustomAttributes" returns attributes in random order.
For example following code will print different results every time I run application.
foreach(var att in attributes)
{
Console.WriteLine(att.Name);
}
On time, first "A" then "B" another time vice versa.
Is there any solution for my problem ?
I'm not going to add a column such as order or anything like that, I'd like to solve the problem.
Environment: .NET 4.5.1 , Visual Studio 2012 Update 3 SDK , C# 5. Both Debug and Release modes.
I don't think there is anything in the documentation anywhere that guarantees that custom attributes will be returned in any particular order. If you need ordered attributes, add an
Order
member to your attribute class.