Search code examples
c#.netvb.netattributescompiler-warnings

Custom Compiler Warnings


When using the ObsoleteAtribute in .Net it gives you compiler warnings telling you that the object/method/property is obsolete and somthing else should be used. I'm currently working on a project that requires a lot of refactoring an ex-employees code. I want to write a custom attribute that I can use to mark methods or properties that will generate compiler warnings that give messages that I write. Something like this

[MyAttribute("This code sux and should be looked at")]
public void DoEverything()
{
}
<MyAttribute("This code sux and should be looked at")>
Public Sub DoEverything()
End Sub

I want this to generate a compiler warning that says, "This code sux and should be looked at". I know how to create a custom attribute, the question is how do I cause it to generate compiler warnings in visual studio.


Solution

  • Update

    This is now possible with Roslyn (Visual Studio 2015). You can build a code analyzer to check for a custom attribute


    Original outdated answer:

    I don't believe it's possible. ObsoleteAttribute is treated specially by the compiler and is defined in the C# standard. Why on earth is ObsoleteAttribute not acceptable? It seems to me like this is precisely the situation it was designed for, and achieves precisely what you require!

    Also note that Visual Studio picks up the warnings generated by ObsoleteAttribute on the fly too, which is very useful.

    Don't mean to be unhelpful, just wondering why you're not keen on using it...

    Unfortunately ObsoleteAttribute is sealed (probably partly due to the special treatment) hence you can't subclass your own attribute from it.

    From the C# standard:-

    The attribute Obsolete is used to mark types and members of types that should no longer be used.

    If a program uses a type or member that is decorated with the Obsolete attribute, the compiler issues a warning or an error. Specifically, the compiler issues a warning if no error parameter is provided, or if the error parameter is provided and has the value false. The compiler issues an error if the error parameter is specified and has the value true.

    Doesn't that sum up your needs?... you're not going to do better than that I don't think.