Attribute in c#:

In this post, we will learn about Attribute in c#: with an example.
-An attribute is a declarative tag that can be used to provide information at runtime about the behaviors of
various component like classes, methods, structures, enumerators and assemblies etc.
– A declarative tag is specified by square ([ ]) brackets placed above the component it is used for.
– Attributes are used for adding some extra information , such as compiler instruction and
other metadata such as comments, description, methods and classes to a program.
– For instance below is a simple class where “GetData” is decorated by the “Obsolete” attribute.

Now, Open visual studio and create console application and write below line of code,

public class Example
{
        [Obsolete]
        public void GetData()
        {
        }
        public void GetNewData()
        {
        }
}

– Now, if someone is trying to create object of above class(Example) and tries to call GetData method then he will alert
that this method is Obsolete.
– One can also provide some message along with this attribute, like below.

[Obsolete("Please use GetNewData",true)]
public void GetData()
{

}

– This attribute will make sure that this method must not be called as ‘true’ is specified along with attribute.Still if any
one tries to call then it will throw an exception.

I hope you get an idea about Attribute in c#.
I would like to have feedback on my blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you liked this post, don’t forget to share this.