Friday, January 11, 2019

Attributes In C#


Attributes – Used to provide the information to compiler about the behavior of class/assemblies and this information can be used by the reflection. You can find more information about Reflection here

Example
1.       Obsolete
2.       WebMethod
3.       Serializable
How to use Obsolete Attribute


class Program
    {
        int result = new Calculator().AddTwoNumbers(1,2);
    }
   
    public class Calculator
    {
        [Obsolete("This method is obsolete, Use new method AddNumbers(List)")]
        public int AddTwoNumbers(int num1, int num2)
        {
            return num1+num2;
        }

        //Add a method to add N numbers and it will obsolute the AddNumbers(int,int)
        public int AddNumbers(List<int> numbers)
        {
            int total = 0;
            foreach(var num in numbers)
            {
                total += num;
            }
            return total;
        }
    }

Furthermore, if you want to restrict user not to use the obsolete method you can pass the second Boolean parameter like below

[Obsolete("This method is obsolete, Use new method AddNumbers(List)",true)]

No comments: