2

I have a function which should only be used by a developer in special circumstances.

Unfortunately setting public / private doesn't really help, as it needs to be visible for use in many cases.

I have documented the function with xmldocs to give the developer a warning, but is it possible to output a compiler warning? Perhaps using an attribute, similar to marking a function as obsolete?

Or perhaps if someone has any useful architectural advice on steering people away from dangerous methods (i'm guessing this will probably be separate namespaces, inheritance etc?)


ADDITIONAL DETAIL

Thanks for the answers guys, lots of 1+'s from me :-)

It's also helped me clarify my question:

[Obsolete("my message")] is better in some ways to #warning, as it will only display a warning if the method is actually being used. However as ChrisF points out, it isn't actually an Obsolete method, so isn't really accurate.

Is there a middle ground between the functionality of [Obsolete("my message")] but without the meaning?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Alex KeySmith
  • 16,657
  • 11
  • 74
  • 152

6 Answers6

3

You can use #warning ...

More info at http://msdn.microsoft.com/en-us/library/963th5x3(v=vs.100).aspx

Adi Lester
  • 24,731
  • 12
  • 95
  • 110
Thomas
  • 1,281
  • 8
  • 22
3

In Visual Studio you can throw errors and warnings like this.

#warning This line is a compiled warning

I am not sure if you can do it conditional, but this will throw a warning when compiling.

Schalk
  • 144
  • 5
1

I think the best way to solve this is to write a small Roslyn Analyzer and ship that with your library. That way you can generate custom code inspections and that also allows the developer to suppress your warning with a proper Reason using the Suppress attribute.

Examples can be found here: https://msdn.microsoft.com/magazine/dn879356.aspx.

jessehouwing
  • 106,458
  • 22
  • 256
  • 341
0

Use the Obsolete attribute:

[Obsolete("Please don't use this")]
public void DodgyMethod()
{
}

Any code that attempts to call the method will cause the compiler to issue a warning.

While it's not technically an obsolete method, the effect is the same.

ChrisF
  • 134,786
  • 31
  • 255
  • 325
0

You should add [Obsolete("Don't use this outside of whatever")] to the method.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
0

Using Obsolete is indeed a good solution.

And you can still call this method yourself, by disabling the warning just for the call:

#pragma warning disable CS0618
DodgyMethod();
#pragma warning restore CS0618
Alexis Pautrot
  • 1,128
  • 1
  • 14
  • 18