Reputation: 147
I have the following custom attribute that I would like to have a type name as a property. However, I do not want to have to use the string representation of the type when using the attribute. Example:
public class HelpMeAttribute : Attribute
{
public string TypeName { get; set; }
}
And to use it, I thought this
[HelpMe(TypeName = typeof(MyClass2).FullName]
public class MyClass1
{
}
public class MyClass2
{
}
I get the error: "An attribute must be a constant expression, typeof expression or array creation expression of an attribute parameter type."
I would prefer not to do:
[HelpMe(TypeName = "MyClass2"]
because that seems bad to have the type in a string. Better to let the compiler check that the type I am putting in the attribute exists.
Can someone point me down the path of enlightenment to fix this?
Upvotes: 1
Views: 478
Reputation: 149058
Attribute initializers can only use compile-time constants or System.Type
properties.
So why not just use Type
?
public class HelpMeAttribute : Attribute
{
public Type Type { get; set; }
...
public HelpMeAttribute()
{
}
}
...
[HelpMe(Type = typeof(MyClass2))]
public class MyClass1
{
}
Upvotes: 1