9 Replies - 567 Views - Last Post: 01 November 2013 - 08:06 PM Rate Topic: -----

#1 adn258  Icon User is offline

  • D.I.C Addict

Reputation: 11
  • View blog
  • Posts: 762
  • Joined: 31-August 11

Why Should you Use Attributes In C#?

Posted 30 October 2013 - 02:02 AM

So I understand how attributes work here in C# and I see them used for Interop for calling on Win32 stuff but other than those RARE circumstances I rarely see them used. Why are they used so rarely and why do I find that they are almost NEVER necessary in any programs that I write?

For Examples: http://msdn.microsof...4(v=vs.71).aspx

Is This A Good Question/Topic? 0
  • +

Replies To: Why Should you Use Attributes In C#?

#2 Momerath  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1010
  • View blog
  • Posts: 2,444
  • Joined: 04-October 09

Re: Why Should you Use Attributes In C#?

Posted 30 October 2013 - 04:40 AM

Most programs don't need Reflection, so most programs don't need attributes.
Was This Post Helpful? 1
  • +
  • -

#3 Curtis Rutland  Icon User is offline

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 4496
  • View blog
  • Posts: 7,845
  • Joined: 08-June 10

Re: Why Should you Use Attributes In C#?

Posted 30 October 2013 - 07:55 AM

Attributes are metadata. Most applications don't need any extra information about its objects. Some do. You've mentioned Interop, so I'm assuming you mean DllImport. But there are plenty more built-in features that use attributes.

ASP.NET MVC is a perfect example. You tell your controller methods what type of HTTP verb to respond to:

[HttpPost]
public ActionResult DoPost(string someParam){
  ...
}


Also, it's heavily used in WCF. You have to mark your interface as a [ServiceContract], each web method as [ServiceOperation], classes you want to be serialized as [DataContract], and members of that class you want included in serialization as [DataMember].

The point is, they are more widespread than you realize, but they are for a very specific purpose: to provide extra information about certain code objects.
Was This Post Helpful? 1
  • +
  • -

#4 lordofduct  Icon User is offline

  • I'm a cheeseburger
  • member icon


Reputation: 2533
  • View blog
  • Posts: 4,633
  • Joined: 24-September 10

Re: Why Should you Use Attributes In C#?

Posted 30 October 2013 - 08:41 AM

I use them rather frequently. Like Curtis Rutland said with WCF they're used quite a bit.

I also use them frequently in several game engines and frameworks that are built with C# as its scripting language, or even as its root (with XNA).

I often use them with serialized objects as well (which can be related to WCF and games and other things as well).

I even have several of my own custom attributes to use with various things I've written.

For instance I have a FormManager that handles opening and maintaining forms in a project. Each form can have a rule associated with it. To associate a rule I attribute it the form as an 'ExFormOpenRuled', which has a couple properties including a reference to the type of the rule to be used for this form. This way the formmanager can reflect off the type of the form being opened if a rule exists, create an instance of that rule, and operate the rule at various events in the life of the form.

Another custom attribute set I have deals with the same system. The formmanager works in tandem with a navigation system that can tell the formmanager what to do and what to open. The navigation system is configured via XML, and I need to allow for string representations of commands in the xml. I also want the ability to add commands easily. So I have an attribute to define a class that contains available commands, and an attribute for functions that represent the command. Then I can load up this class of methods and when a command comes in I search its methods for one with an attribute that has its command name declared. So then it knows what code to run when a specific command is entered in the XML and the nav link that is generated from that entry is selected (such as an entry in the menu tree).
Was This Post Helpful? 2
  • +
  • -

#5 AdamSpeight2008  Icon User is offline

  • MrCupOfT
  • member icon


Reputation: 2263
  • View blog
  • Posts: 9,468
  • Joined: 29-May 08

Re: Why Should you Use Attributes In C#?

Posted 30 October 2013 - 02:32 PM

Also remember attributes ain't specific to C#, it's a .net framework thing.

In VB.net you need to use <System.Runtime.CompilerServices.Extension>()>

Or the mark a method as <Obselete()>

You can even implement your own if you inherit from the Attribute base class.

<AttributeUsage(AttributeTargets.Class or AttributeTargets.Method ,AllowMultiple:=True,Inherited:=False)>
Public Class AuthoredByAttribute
  Inherits Attribute 
  Protected _Name As string
  Public Sub New(Name As String)
    MyBase.New
    _Name=Name 
  End Sub
  Public ReadOnly Property Name As String
   get
  return _Name
  end Get
    End Property 
End Class


in use
  <AuthoredBy("AdamSpeight2008")>
Public Sub SayHello()
  Console.Writeline("Hello World!")
End Sub


Was This Post Helpful? 1
  • +
  • -

#6 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3589
  • View blog
  • Posts: 11,157
  • Joined: 05-May 12

Re: Why Should you Use Attributes In C#?

Posted 30 October 2013 - 10:21 PM

I use attributes all the time to mark my unit tests so that xUnit can find and invoke them.
Was This Post Helpful? 1
  • +
  • -

#7 adn258  Icon User is offline

  • D.I.C Addict

Reputation: 11
  • View blog
  • Posts: 762
  • Joined: 31-August 11

Re: Why Should you Use Attributes In C#?

Posted 31 October 2013 - 12:14 AM

Thanks for your help guys but I'm still failing to see WHY you would need reflection which I guess is changing object parts at runtime but you could simply use a property to change something why do you NEED attributes and how are they any help I'm just not getting that?
Was This Post Helpful? 0
  • +
  • -

#8 lordofduct  Icon User is offline

  • I'm a cheeseburger
  • member icon


Reputation: 2533
  • View blog
  • Posts: 4,633
  • Joined: 24-September 10

Re: Why Should you Use Attributes In C#?

Posted 31 October 2013 - 11:59 AM

View PostAdamSpeight2008, on 30 October 2013 - 04:32 PM, said:

Also remember attributes ain't specific to C#, it's a .net framework thing.

In VB.net you need to use <System.Runtime.CompilerServices.Extension>()>

Or the mark a method as <Obselete()>

You can even implement your own if you inherit from the Attribute base class.

<AttributeUsage(AttributeTargets.Class or AttributeTargets.Method ,AllowMultiple:=True,Inherited:=False)>
Public Class AuthoredByAttribute
  Inherits Attribute 
  Protected _Name As string
  Public Sub New(Name As String)
    MyBase.New
    _Name=Name 
  End Sub
  Public ReadOnly Property Name As String
   get
  return _Name
  end Get
    End Property 
End Class


in use
  <AuthoredBy("AdamSpeight2008")>
Public Sub SayHello()
  Console.Writeline("Hello World!")
End Sub



Very true, I actually should have said, my custom attributes relating to the 'formmanager' I spoke of are actually written in VB.Net.

I write VB.Net for my day job, and C# for my at home projects.
Was This Post Helpful? 0
  • +
  • -

#9 Curtis Rutland  Icon User is offline

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 4496
  • View blog
  • Posts: 7,845
  • Joined: 08-June 10

Re: Why Should you Use Attributes In C#?

Posted 31 October 2013 - 12:13 PM

The why is all about metadata.

Quote

but you could simply use a property to change something


Sure, for some things. But for some, that's completely impossible. WCF is a perfect example. Read this thread:

http://stackoverflow...erationcontract

What happens behind the scenes is that the WPF framework gets told (through configuration) that it is supposed to use this particular assembly as a service. It then has to use Reflection to find which Interfaces are defined as [ServiceContracts], so it knows to make a service for that particular contract. It knows which methods to make into service operations because they're marked with [OperationContract]. It knows which Types need to be included in the WSDL it generates because they're marked with [DataContract], and it knows which properties/fields of that type should be included in the graph, because they're marked as [DataMember].

It's basically generic programming on steroids. Another great example is the Managed Extensibility Framework (a.k.a. MEF). The general idea is that you can make "plugins" with this.

High level: attributes provide extra information about your code that can't be contained inside the objects themselves.
Was This Post Helpful? 2
  • +
  • -

#10 tlhIn`toq  Icon User is offline

  • Please show what you have already tried when asking a question.
  • member icon

Reputation: 5535
  • View blog
  • Posts: 11,857
  • Joined: 02-June 10

Re: Why Should you Use Attributes In C#?

Posted 01 November 2013 - 08:06 PM

What someone will 'get' is a function of their experience and their needs.
As a beginner, or someone just writing code by themselves you have a different experience and need than a team of developers in a company.

My company has several developers, in 3 states. We run automated testing (testing as a reason mentioned earlier), that happens on a dedicated build machine nightly.

Because we have a mix of C++ and C# in our overall solution all enums, and language localization strings are defined in XML files, that then use automated tools to generate either C++ or C# files for each project. All of that uses attributes.

Like I said... Its all about the perspective of where you are looking from new or experienced coder, working alone or on a team, on small or large projects, with or without automation... etc.

A person whose total photo needs are handled by a camera phone doesn't grasp the need for a $5,000 DSLR. A person in New York city who takes cabs and at most rides a bike can't fathom why I own a mega-cab dually pickup.

Until you are in a company working on projects that need these things and can experience it first hand, you really won't 'get' it. Just like a virgin will never truly 'get' the reality of sex no matter how much they read about it. Some things just have to be experienced.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1