Question

Possible Duplicate:
.NET: What are attributes?

What do the square brackets mean in the following code:

public class LoginModel
{
    [Required]
    [Display(Name = "User name")]
    public string UserName { get; set; }

    [Required]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [Display(Name = "Remember me?")]
    public bool RememberMe { get; set; }
}

I have read in other questions that they are attributes, but I don't know how they work..why do they appear in this class? And are these only used in C#?

Was it helpful?

Solution

The basic idea is you are marking up your code. How they work is up to "you"

Say you were building several forms for data entry to several classes, and you wanted to display a hint against mandatory ones and do a validation against them, and you wanted the code to do this to be common to all classes you were doing forms for and you definitely did not want to change that routine every time you added a new mandatory property to anyone of your classes.

Using reflection, you can pass an object to a routine, get a list of all it properties, find all those with a [Required] attribute even test the instance to see it it's not blank, and pass a list of them back without having to know anything about the class. Not which it is , not how many if any properties it has, what type they are. The only shared code is the RequiredAttribute class.

Easiest way to learn it is to define one of your own and use it.

Google .Net System.Attribute, examples abound.

OTHER TIPS

They are called Attributes. Look at MSDN.

An attribute is defined by a class that inherits (directly or indirectly) from the abstract class System.Attribute. To attach an attribute to a code element, specify the attribute’s type name in square brackets, before the code element.


And are these only used in C#?

No. Java also has attribute class. Other oop language can also have.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top