Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 950
IWriteApps Avatar asked May 30 '12 17:05

IWriteApps


People also ask

What is the use of obsolete in C#?

An obsolete attribute, in C#, is a declarative tag used while declaring a type or a member of a type to indicate that it should no longer be used.

How do you make a method obsolete in C#?

We can make a method obsolete by putting [Obsolete] attribute on the top of the method.

How do you mark a method obsolete?

The shortest way is by adding the ObsoleteAttribute as an attribute to the method. Make sure to include an appropriate explanation: [Obsolete("Method1 is deprecated, please use Method2 instead.")] public void Method1() { … }

What is system obsolete?

Obsolete refers to outdated computer hardware, software, technology, services or practices that are no longer used, even if they are in working condition. A technology often becomes obsolete when replaced by a newer or better technology.


2 Answers

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.

like image 146
Marc Gravell Avatar answered Oct 26 '22 06:10

Marc Gravell


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

like image 33
Guffa Avatar answered Oct 26 '22 04:10

Guffa