Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interface method marked as Obsolete does not issue a message from the compiler when implemented

Consider this example

    public interface IAnimal
    {
        [Obsolete("Animals can't eat anymore", true)]
        void Eat();
    }

    public class Animal : IAnimal
    {
        public void Eat()
        {
            Console.WriteLine("Hello");
        }
    }

I have an interface IAnimal with an obsoleted method. The Class Animal implements that interface.

Later on, i call the Eat method as such:

var animal = new Animal();
animal.Eat();

The compiler does not fail to compile (i have Obsolete marked to give an error instead of an warning). The program compiles and the method is invoked with no errors, as well.

As far as i can see this is a bug from the compiler. Am i missing anything?

Note: i am using VS2010

like image 968
Luis Filipe Avatar asked Mar 22 '13 00:03

Luis Filipe


People also ask

How do you you specify that a method is obsolete in C#?

The Obsolete attribute decorates a program element by putting the word “Obsolete” above it inside square brackets. Since it is an attribute, we can use either Obsolete or ObsoleteAttribute. [Obsolete] − is a no parameter constructor and is a default using this attribute.

How do you mark obsolete code?

In you examples the "Method1 is deprecated" part is rather redundant. By marking it as obsolete you are saying that it is indeed obsolete, so no need to restate it in the message. Especially since the resulting warning/error will read 'Method1' is obsolete: 'Method1 is deprecated, please use Method2 instead.


2 Answers

You've only marked IAnimal.Eat as obsolete, not Animal.Eat. The var keyword resolves to Animal, and so when you call animal.Eat, you're not calling into any method marked as Obsolete.

To fix, either explicitly change var to IAnimal, or better still, mark Animal.Eat as obsolete as well:

    public interface IAnimal
    {
        [Obsolete("Animals can't eat anymore", true)]
        void Eat();
    }

    public class Animal : IAnimal
    {
        [Obsolete("Animals can't eat anymore", true)]
        public void Eat()
        {
            Console.WriteLine("Hello");
        }
    }
like image 173
SecurityMatt Avatar answered Oct 12 '22 02:10

SecurityMatt


It looks like the behavior is because your var animal is an Animal in which the Eat method is not obsolete. If you did:

IAnimal animal = new Animal();
animal.Eat();

you should see the warning/error that you expect.

like image 21
DocMax Avatar answered Oct 12 '22 01:10

DocMax