Combining multiple attributes

Combining multiple attributes into a single line

Home DailyDrop

Daily Knowledge Drop

When multiple attributes are applied to a program entity, the attributes can either be specified on separate lines, or on a single line.


Multiline

In this example, a class is used to demonstrate an entity having multiple attributes, but the same applies to other relevent program entities:

[Serializable]
[Obsolete]
[DebuggerDisplay("Id={Id}, Name={Name}")]
public class MultiAttributeClass
{
    public int Id { get; set; }

    public string Name { get; set; }
}

Three attributes added to the class - the actual attributes themselves are not important, it could be been any number of any attributes.


Single line

The multiple attributes can also be applied as follows though:

[Serializable, Obsolete, DebuggerDisplay("Id={Id}, Name={Name}")]
public class MultiAttributeClass
{
    public int Id { get; set; }

    public string Name { get; set; }
}

Does this reduce the number of lines in code? Yes Does it make it more difficult to read? Potentially Is this recommended? Probably not. But you can if you want


Notes

A very small knowledge drop today, but something I was not aware was possible. As mentioned, as a general rule I would argue this make the code slightly less readable - however, some might find this code cleaner and more readable.


References

Reddit Post

Daily Drop 227: 04-01-2023

At the start of 2022 I set myself the goal of learning one new coding related piece of knowledge a day.
It could be anything - some.NET / C# functionality I wasn't aware of, a design practice, a cool new coding technique, or just something I find interesting. It could be something I knew at one point but had forgotten, or something completely new, which I may or may never actually use.

The Daily Drop is a record of these pieces of knowledge - writing about and summarizing them helps re-enforce the information for myself, as well as potentially helps others learn something new as well.
c# .net attribute attributes