Tomtom
Tomtom

Reputation: 9384

Attribute to generate compilerwarning for a method in class

I have a class, where I use the singleton-pattern. The class looks like

public class MessageAccess
{
    private static MessageAccess instance;
    public static MessageAccess Instance
    {
        get { return instance ?? (instance = new MessageAccess()); }
    }

    private MessageAccess()
    {

    }

    public void Initialize(string data)
    {
        //...
        isInitialized = true;
    }

    private bool isInitialized;

    public void ReadData1()
    {
        // This Method can always be called
    }

    public void ReadData2()
    {
        // This Method can only be called, if Initialize was called. Otherwise an exception will be thrown
    }
}       

Is it possible to generate a compiler-warning if the Method Initialize is never called

Upvotes: 1

Views: 149

Answers (2)

Piotr Justyna
Piotr Justyna

Reputation: 4966

While I understand your point of view, I don't think such warning would be as handy as you think. I'm afraid .NET framework doesn't cater for this type of warnings for a couple of well defined reasons (please refer to this link: http://blogs.msdn.com/b/csharpfaq/archive/2004/03/19/why-doesn-t-c-warn-about-unused-methods.aspx).

One might think that the lack of this feature is a missed opportunity, but it's not quite the case. Your class, MessageAccess, is public and will be compiled into (let's say) a dll. Even if you had this warning while compiling your dll, you wouldn't want it to appear while compiling some external code using that dll's Initialize method (which is also public). You basically can't guarantee that no other code will ever use that method, and this is one of the better reasons not to have this warning.

Upvotes: 2

Henrik
Henrik

Reputation: 23324

If the class is not used from outside the assembly, you can make it internal. In this case, Code Analysis will generate a warning "Avoid uncalled private code", if the method is not called.

Upvotes: 1

Related Questions