0

I have a enum Color:

enum Color {
    red,
    blue,
    noColor    // This will be deprecated.
}

And a function PrintColor:

public void PrintColor(Color color) {
    Console.WriteLine(color);
}

Because I want to noColor to be deprecated, so I don't allow PrintColor's parameter color to be Color.noColor. Is it possible to be checked by Roslyn that when color would be Color.noColor, we raise an error at compile time?

comments

I think this one is easy to check:

PrintColor(Color.noColor);

But how to check this one:

public void GetNoColor() => Color.noColor;
PrintColor(GetNoColor());
Caesium
  • 789
  • 3
  • 7
  • 24
  • Just to be clear do you want to alert [this cases](https://pastebin.com/KU44pjpM) and more difficult cases? If true it seems that you need to use static analysis of program's control and data flows and keep the state of values and in this case `Roslyn` just will be a small piece of solution. If you just want to alert cases when `Color.noColor` is used directly I can suggest you to find all usages of `noColor` with `Roslyn` (check the FindReferencesAsync) and alerts them. – George Alexandria Feb 02 '19 at 11:45
  • Almost just this case. But there are some existing methods can still use Color.noColor, only no further newly added classes or methods can use noColor. I think find all the reference works! But is it possible to allow some existing methods or instances to use noColor? Can we check the class name the findReferencesAsync returns? Thanks a lot! – Caesium Feb 02 '19 at 12:59
  • `FindReferencesAsync` returns a collection of `ReferencedSymbol` which contains `ISymbol` which uses `noColor`, so yes, you can confirm that the returned symbol is from your "allowed list" (by comparing names, signatures and so on) or his declaring type symbol from this list. – George Alexandria Feb 02 '19 at 14:00
  • I think it works! Thanks a lot! – Caesium Feb 02 '19 at 14:04

1 Answers1

1

If you don't want some type's member to be used, you can just use the ObsoleteAttribute.

Paulo Morgado
  • 14,111
  • 3
  • 31
  • 59