smwikipedia
smwikipedia

Reputation: 64363

What typical usage does the attributes like [Description] have?

I see some code snippets like this:

[Description("This method is used to do something.")]
static void SomeMethod()
{
}

I am wondering if what we want is just to describe the meaning of the method, why not just use the following comments:

/// <summary>
/// This method is used to do something.
/// </summary>
static void SomeMethod()
{
}

Actually, the comment style can be leveraged by IntelliSense. So why do we bother to use an attribute?

Update

So, though not very accurate, I take Attributes as run time version of comment. While comment is only for edit time.

Upvotes: 0

Views: 34

Answers (2)

Andrew
Andrew

Reputation: 3806

Also it's a good mechanism to provide supporting information about the property if you are implementing a user control and want your property to show extra description in Properties Window. You can combine this attribute with CategoryAttribute to group Properties into categories in Properties Window

http://msdn.microsoft.com/en-us/library/system.componentmodel.descriptionattribute%28v=vs.110%29.aspx

Upvotes: 1

Tim S.
Tim S.

Reputation: 56556

Attributes like [Description] can be accessed at runtime, while comments cannot. For example, this answer shows you how to get the description from an enum (and other answers there show how to parse an enum from its description). E.g. such an enum might look like:

public enum Fruit
{
    [Description("Apples are red or green, and tasty")]
    Apple,
    [Description("Pineapples are yellow inside, and acidic")]
    Pineapple,
}

Here's how it might look with your method's description:

var desc = typeof(ThatClass)
   .GetMethod("SomeMethod", BindingFlags.Static | BindingFlags.NonPublic)
   .GetCustomAttributes(typeof(DescriptionAttribute))
   .Cast<DescriptionAttribute>().ToList();
Console.WriteLine(desc[0].Description);
// prints "This method is used to do something."

I don't see much of a point to having it on a method, except in some unusual cases, but it has its uses and is quite distinct from a comment.

Upvotes: 0

Related Questions