Uses for [Obsolete(string, bool)] attribute for .NET

1k views Asked by At

Note: I already checked msdn, it doesn't address my actual question, see below.

I'm trying to use the obsolete attribute on a (obviously obsolete) constructor in one of my classes. Here's the scenario:

I want to be able to force the developer to update to the new constructor without affecting already existing and deployed code. This way I can deploy my code to production just fine, but from a developers perspective, whenever they go into their code, instead of just getting a "warning" which I'm sure they'll just ignore, I want them to get a compile error because the status quo is no longer ok.

So my question is, will this affect only developers, or all calling apps, or do I have the whole thing wrong?

sample code:

public class MyClass
{
   private string _userID; //new code

   [Obsolete("This constructor is obsolete, please use other constructor.", true)]
   public MyClass()
   {
      _userID = ""; //defaulting to empty string for all those using this constructor
   }

   public MyClass(string userID)
   {
      _userID = userID; //this is why they need to use this constructor
   }
}

Any and all help will be appreciated, thanks in advance!

4

There are 4 answers

0
Marc Gravell On BEST ANSWER

Yes, this primarily affects the compiler - any pre-built code won't be affected... unless that code explicitly checks for this attribute. For example, some serialization code (XmlSerializer, IIRC) checks for this - so it might not be entirely side-effect free... but in principal existing code won't usually be affected until they try to compile next.

Of course, if you are using this code from something that uses dynamic compilation (for example ASP.NET without pre-compile) then all bets are off.

0
Guffa On

The attribute is only an instruction to the compiler. Already existing binaries can still use the constructor.

0
Reed Copsey On

So my question is, will this affect only developers, or all calling apps, or do I have the whole thing wrong?

This will only be used at compile time, by the compiler. It will not affect applications which have already been deployed.

As such, this will have the behavior you are trying to accomplish.

3
Hans Passant On

This is what [Obsolete] already does, no extra help is needed. It is not a compile time warning, it generates an error:

error CS0619: 'ConsoleApplication1.MyClass.MyClass()' is obsolete: 'This constructor is obsolete, please use other constructor.'