Attribute to generate compilation error when calling a method?

I would like to make sure that the method (actually the constructor in my case) is never called explicitly from code. It should only be called through reflection at run time. For this, I would like to apply a method attribute that generates a compiler error if the method is called, for example:

[NotCallable("This method mustn't be called from code")] public void MyMethod() { } 

I know that I could make the method private, but in this case I could not call it a reflection in the partial context of trust ...

For completeness, here is more detailed about why I need it:

I am implementing a reusable Singleton<T> class based on an article by John Skeet . Here is my code:

 public static class Singleton<T> { public static T Instance { get { return LazyInitializer._instance; } } private class LazyInitializer { // Explicit static constructor to tell C# compiler // not to mark type as beforefieldinit static LazyInitializer() { Debug.WriteLine(string.Format("Initializing singleton instance of type '{0}'", typeof(T).FullName)); } internal static readonly T _instance = (T)Activator.CreateInstance(typeof(T), true); } } 

(Notice how I create an instance of T using Activator.CreateInstance )

Then I can use it with a class like this:

 private class Foo { protected Foo() { } public string Bar { get; private set; } } 

And call Singleton<Foo>.Instance to access the instance.

In partial trust, it will not work, because the Foo constructor is not public. But if I make it public, nothing will explicitly call it from the code ... I know that I could use the ObsoleteAttribute constructor in the Foo constructor, but it will generate a warning, and many people simply ignore the warnings.

So, is there an attribute similar to ObsoleteAttribute that generates an error instead of a warning?

Any suggestion will be appreciated.

+4
source share
1 answer

You can use the ObsoleteAttribute constructor, which takes a boolean, with which you can indicate that the method call is a compilation error:

 [Obsolete("Don't use this", true)] 

However, if I were you, I would revise my design, as this is not a sign of a well-designed API.

+7
source

Source: https://habr.com/ru/post/1301257/


All Articles