Reputation: 715
I have a class with a custom attribute defined like this:
[AttributeUsage(AttributeTargets.Property)]
public class MyAttribute : Attribute
{
private string name;
public MyAttribute(string name)
{
this.name = name;
}
}
public class MyClass
{
[MyAttribute("ClassName")]
public string ClassName { get; set; }
}
Visual Studio highlights the line
[MyAttribute("ClassName")]
with this message:
IDE0001 : Name Can Be Simplified.
It suggests to shorten the attribute definition to My("ClassName") which doesn't work because the attribute is not defined as "My".
This suggestion seems to be based on the way the default attributes are implemented where either MyAttribute or My could be used. How would I implement my custom attribute to accept either My or MyAttribute like the default attributes do?
Upvotes: 3
Views: 3073
Reputation: 54618
Typically when you derive from attribute you do not use the suffix Attribute
when using it:
public class MyClass
{
[My("ClassName")]
public string ClassName { get; set; }
}
It suggests to shorten the attribute definition to My("ClassName") which doesn't work because the attribute is not defined as "My".
(It's compiler magic, and it works)
How would I implement my custom attribute to accept either My or MyAttribute like the default attributes do?
You already did, you can use [MyAttribute("whatever")]
and it will compile just fine.
Upvotes: 7