none
What's the difference between Porperty and Attribute?

    Question

  • I am very confused about these two. What's difference? When to use property? When to use attribute?

    Thanks
    Saturday, June 21, 2008 3:40 AM

Answers

  • Hi,

    There's a lot of difference between a C# property and attribute. A property lets you get/set data in your class.  However, an attribute allows you to decorate elements of your code with declarative information.  i.e. here's  a class with three properties:

    public class Customer
    {
        public string Name { get; set; }
        public string Email { get; set; }
        public string Address { get; set; }
    }

    and you use it like this:

    var cust = new Customer();

    cust.Name = "Some Name";

    Console.WriteLine("Name: " + cust.Name);

    However, an attribute is much different and the attributes you use depend on the tool you are using.  For example, if you had a method you wanted to deprecate from your application, you could use the Obsolete attribute like this:

    [Obsolete("Method deprecated - Please use MethB instead")]
    public void MethA() { ... }

    If you were writing unit tests in VS2008, you would use Test and TestMethod attributes like this:

    [Test]
    public class MyTestClass
    {
        [TestMethod]
        public void MyTestMethod() { .... }
    }

    To summarize, attributes support tools that operate on your code, but properties define the state of an object and there is no logical comparison between the two.

    Because of this difference in purpose and the fact that you asked a question that sounds like you feel they are similar, I wonder what you meant by the term "attribute".  It almost sounds like you were really wanting to know the difference between fields and properties.  Just in case, that was really your question: a field gives calling code direct access to the data in your class, but a property allows you to control access to that value.  If the underlying representation of the data changes, then a field would cause calling code to break, which could cause a rippling effect through your code for trying to fix the change.  If someone else's code depends on that field, then their code would break, which means that you might not be able to change your class.  If you use a property, you can manipulate the representation of the data in the property accessors if there ever was a change and calling code would never know, which gives you more maintainable code.  For this reason, I tend to use properties as a general preference over fields.  I won't go as far as to suggest that you should never use a *public* field, because someone might have a valid use case for it (in a limited scenario), but I still think that for general software development the property will serve you better.

    Joe
    http://www.csharp-station.com
    • Marked as answer by Zhi-Xin Ye Monday, June 23, 2008 8:26 AM
    Saturday, June 21, 2008 5:54 PM