5

I'm a C# newbie. Saw this piece of code in an open source

public class Staff : BusinessObjectBase
{

    /// <summary>
    /// Column: StaffID(Identity)(Primary Key), Allow DBNull=False
    /// </summary>
    [DataMap("StaffID", IsIdentity=true, IsReadOnly=true, IsKey=true)]
    public System.Nullable<System.Int32> StaffID { get; set; }

    /// <summary>
    /// Column: TeamID, Allow DBNull=True
    /// </summary>
    [DataMap("TeamID", AllowDBNull=true)]
    public System.Nullable<System.Int32> TeamID { get; set; }

The lines start with open square brackets, what are they doing? reference to parent object's attributes? If so, why are they neccessry? Is there a name of this style of coding? Thank you!

KTmercury
  • 93
  • 3

5 Answers5

10

This all falls under a concept known as metaprogramming. There is a book called Metraprogramming in .NET (Manning). You're basically annotating your code with data that can later be interpreted at runtime by some other code via reflection. This is popular in Java and Ruby as well. You'll see it in ASP.NET MVC, WCF, and much more. It also introduces another programming practice known as Declarative Programming. You say "what you want to do", and let something else determine "how". It's really big in functional programming languages and just programming in general for that matter. See this post about how to parse the attributes. How do I GetCustomAttributes?

Community
  • 1
  • 1
A-Dubb
  • 1,670
  • 2
  • 17
  • 22
4

Those are called attributes--see MSDN.

Isaac Overacker
  • 1,385
  • 10
  • 22
4

Read all about C# Attributes. They're basically instances of classes that attach themselves to other properties/methods/classes/code elements. In this case, put simply, you defined a new field called StaffID of type System.Nullable<...> that has a DataMap object attached to it.

qJake
  • 16,821
  • 17
  • 83
  • 135
3
Data Annotations to Customize Data Classes

http://msdn.microsoft.com/en-us/library/dd901590(v=vs.95).aspx

Doug Chamberlain
  • 11,192
  • 9
  • 51
  • 91
3

They're attributes.

m.edmondson
  • 30,382
  • 27
  • 123
  • 206