Can you omit the bracket from attributes without parameters?

I noticed that when I have [Serializable] instead of [Serializable()] , the code is still compiling.

Is there a rule for this that you can omit parentheses? Is this a good practice? It seems to me more readable if I do not miss something.

+4
source share
4 answers

There is no particular rule regarding the best practices that I have seen anywhere in this subunit.

In general, I believe that people who manually type in their attributes skip empty partners, but code generation almost always explicitly turns them on.

+6
source

Yes, you can omit the brackets.

  [Serializable] [Serializable()] [SerializableAttribute] [SerializableAttribute()] 

There are four ways to write the same attribute.

The general practice is to always omit the Attribute part.
Empty () usually omitted, but it really doesn't matter. And, of course, you will need them to set any parameters or properties.

+6
source

You can skip () if the attribute constructor that you want to use does not have parameters, and you do not want to specify any optional parameters (property values).

See here for more details.

+2
source

Yes, omitting an attribute is legal in terms of language. I donโ€™t know any best practices related to it, but overall I think that developers omit parens if they are not needed.

+1
source

Source: https://habr.com/ru/post/1304163/


All Articles