Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CustomAttribute Name Can Be Simplified

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?

like image 806
lukevp Avatar asked Aug 13 '26 20:08

lukevp


1 Answers

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.

like image 138
Erik Philips Avatar answered Aug 16 '26 09:08

Erik Philips



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!