17

What does it mean to Decorate or add an attribute to a class or parameter?
What's the purpose and when would I do this?

Links to resources and direct answers are welcome.

RBT
  • 24,161
  • 21
  • 159
  • 240
Mark G
  • 557
  • 1
  • 6
  • 17
  • 1
    Looking this? http://www.codeproject.com/Articles/479635/UnderstandingplusandplusImplementingplusDecoratorp – Soner Gönül Jul 03 '15 at 14:00
  • 1
    You can decorate classes and class members with attributes. Basically this attributes are another classes derived from class System.Attribute that provide some extra information. More information you can find here : https://msdn.microsoft.com/en-us/library/aa288454(v=vs.71).aspx – Fabjan Jul 03 '15 at 14:02
  • 2
    In c# this could either mean using Attributes or the decorator pattern. I Suppose what you mean is Attributes since they apply to both Classes and parameters. – nozzleman Jul 03 '15 at 14:18
  • See [here](http://stackoverflow.com/questions/29756038/add-a-badge-to-a-c-sharp-winforms-control/29757940?s=1|0.4928#29757940) for an example of an adorner class that can decorate controls with a clickable badge. Not only would subclassing be over the top, it would also have to be done for all control types necessary.. Note that this is about instances, though – TaW Jul 03 '15 at 14:55

3 Answers3

9

When You add decorator in C# it is like adding a property to the class/method. There will be an attribute attached to it.

If You write Unit test You will meet a simple decorator TestMethod like that:

[TestMethod]
public void TestMethod1()
{
}

The framework will use the decorators to check what test methods are in the test set.

You can check on the attribute here

There is another nice to read article about Writing Custom Attributes

Decorators are not limited to the '[ ]' form of decorators. There is also a design pattern for that, that was already mentioned before by others.

ntohl
  • 2,067
  • 1
  • 28
  • 32
  • This answer is very misleading. Please see [this](https://stackoverflow.com/a/52789179/4228458). – CodingYoshi Oct 13 '18 at 03:23
  • IMHO Attributes in C# _is_ a form of decorator pattern implementation. [with this UML class diagram](https://www.dofactory.com/net/decorator-design-pattern), the reconciliation is the Decorator class is `System.Attribute`, the ConcreteDecoratorA is `Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute`, and the operation is making the method visible to the test runner framework. Because design patterns meant to be for being on the same page when we talk about a thing, it's wrong to say Attributes and Decorators are entirely different concepts. – ntohl Oct 15 '18 at 20:50
  • The only thing, that is missing from "Attach additional responsibilities to an object dynamically", that it's not runtime. Tho [this](https://stackoverflow.com/questions/4842978/decorator-pattern-versus-sub-classing#comment5376986_4843039) comment, and the following answers also states my thought about the problem. Since you have to define Decorators design time, the main advantage is reusability, which is the key concept behind Attributes as well. Attaching it runtime [is still possible](https://stackoverflow.com/a/24413055/1859959) – ntohl Oct 15 '18 at 21:01
  • So what you are saying is if we decorate a property with `[DataMember]`, we just implemented *Decorator Pattern*? – CodingYoshi Oct 15 '18 at 21:12
  • We used an implementation of the Decorator Pattern, which's `addedState` (from the same UML) is used inside WCF's serialization methods with reflection. And IMHO we should always consider implementing an Attribute if we need a decorator in C#, because of the support of the language. – ntohl Oct 16 '18 at 06:44
3

Decorator was one of the original 23 patterns described in the Gang of Four "Design Patterns" book. They describe it well here.

Summary:

Decorator : Add additional functionality to a class at runtime where subclassing would result in an exponential rise of new classes

Patterns are language agnostic. They are descriptions of solutions to common problems in object-oriented programming. It's possible, even preferred, to discuss them without reference to a particular language. The examples in the original book were written in C++ and Smalltalk. Neither Java nor C# existed when the book was first published in 1995.

duffymo
  • 305,152
  • 44
  • 369
  • 561
  • GoF provided a catalog of 23 patterns and not 26. Kindly correct me if I'm wrong - https://circle.visual-paradigm.com/catalog/ – RBT Apr 05 '20 at 06:06
  • 1
    Good answer to a totally different question – edc65 Nov 24 '22 at 14:31
  • How is citing the original formal definition a totally different question? You'll have to do better than this to raise your rep at SO. – duffymo Nov 25 '22 at 23:14
1

Decorating a class means adding functionality to an existing class. For example, you have a class SingingPerson that has a talent of singing.

public class SingingPerson
{
    public string Talent = "I can sing";
    public string DoTalent()
    {
        return Talent;
    }
}

Later on, you decided that the SingingPerson class should also be able to dance but don't want to alter the existing class structure. What you do is you decorate the SingingPerson class by creating another class which contains the added functionality. This new class that you will be creating takes in a SinginPerson object.

public class SingingAndDancingPerson {
    SingingPerson person;
    public string Talent { get; set; }
    public SingingAndDancingPerson(SingingPerson person)
    {
        this.person = person;
    }

    public string DoTalent()
    {
        this.Talent = person.Talent;
        this.Talent += " and dance";
        return this.Talent;
    }
}

When you try to create instances of these classes the output will be the following:

 SingingPerson person1 = new SingingPerson();
        Console.WriteLine("Person 1: " + person1.DoTalent());
        SingingAndDancingPerson person2 = new SingingAndDancingPerson(person1);
        Console.WriteLine("Person 2: " + person2.DoTalent());
        Console.ReadLine();
jmc
  • 1,649
  • 6
  • 26
  • 47
  • But it also means to __not__ subclass, no? – TaW Jul 03 '15 at 14:58
  • @TaW what do you mean by `to not subclass`? – jmc Jul 04 '15 at 13:50
  • For this example to be correct, decorating class must be assignable to the decorated type, either by being derived from it, it implementing the same interface. The whole idea of decorating is to be able to: `IComputer pc = new Computer().AddMouse().AddKeyboard(); if(deluxe) pc = pc.AddRGBLighting();` This won't work when decorators are external classes. – Robert Synoradzki May 22 '19 at 09:19