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
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.
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.
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");
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With