12

I wonder that the obsolete attribute is checked at only runtime?

Think that you have two assemblies. Assembly A uses a method from Assembly B. After that we mark the method in Assembly B as obsolete which causes a compile time error when compiling assembly A.

No problem so far but the question is whether the older assembly A continue to work with new Assembly B or not? Thanks

mkus
  • 3,357
  • 6
  • 37
  • 45

2 Answers2

14

It depends on what you are doing. The [Obsolete] attribute is primarily for use at compile-time, but be aware that some parts of the runtime have different behavior when it is present (see below). It might cause problems, even to existing code that is not rebuilt, so we must conclude that NO, [Obsolete] is not checked only at compile time.

For example, the code below will write Foo but not Bar:

using System;
using System.Xml.Serialization;
public class Data
{
    public int Foo { get; set; }
    [Obsolete] public int Bar {get;set;}

    static void Main()
    {
        var data = new Data { Foo = 1, Bar = 2 };
        new XmlSerializer(data.GetType()).Serialize(Console.Out, data);
    }
}

(XmlSerializer is a runtime too - not part of the compiler)

Caleb Bell
  • 520
  • 6
  • 23
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • Thanks for your detailed response Marc. – mkus May 28 '10 at 13:40
  • 2
    I ran into problems with this. I had marked some entries in an enum with [Obsolete] in a web service. Clients consuming the service would then no longer receive those enum entries at runtime. But the web references would still include them. This seems like a bug in the serialization to me - or a poor design decision at best. Giving this flag runtime significance completely defeats its purpose in my opinion. – LOAS Sep 03 '12 at 05:57
6

Building an assembly that uses a method from another assembly which is marked as Obsolete causes a compile time warning (Unless you have 'display warnings as errors' enabled).

There is nothing stopping you using this method while ever it remains in the referenced assembly. The Obsolete attribute is there as a way for library developers to let the people who use the library know that they should be looking to use a different method to achieve what they need.

To answer your question, yes, an older assembly A will continue to work with a new assembly B. (providing the assembly version remains the same)

Greg B
  • 14,597
  • 18
  • 87
  • 141
  • `[Obsolete("nitpicking", true)]` should give you an error at compile time if referenced directly even if you have _display warnings as errors_ disabled. – mbx Feb 27 '14 at 13:27