Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does this C# feature have a name and what does it do?

Tags:

c#

oop

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!

like image 801
KTmercury Avatar asked Aug 26 '11 20:08

KTmercury


1 Answers

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?

like image 125
A-Dubb Avatar answered Sep 17 '22 10:09

A-Dubb