Friday 30 June 2017

Obsolete Attribute

The obsolete attribute can mark a function in your class as obsolete, it can then be set as deprecated as in you can use it but shouldn't, or marked to create an error.

using System;
using System.Diagnostics;

namespace ConditionalAttributeExample
    public class Person
        //You can use it but shouldn't
        [Obsolete("This Property is obsolete, use FirstName and LastName instead", false)]
        public string FullName { get; set; }

        public string FirstName { get; set; }
        public string LastName { get; set; }
        public DateTime BirthDate { get; set; }

        //You can't use it, will create an error
        [Obsolete("This method is obsolete, use GetAge instead", true)]
        public int GetYearsOld()
            return DateTime.Now.Year - BirthDate.Year;

        public int GetAge()
            var Today = DateTime.Now;
            var age = Today.AddYears(-BirthDate.Year).Year;

            return age;

    class Program
        static void Main(string[] args)
            var p = new Person();
            //will compile with warning
            p.FullName = "Pawel Chooch";

            //will not complie


notice that we mark two properties with the Obsolete attribute, we pass a message to both and then a boolean value representing if it should cause a compile time exception. True causes exception, False is a warning.