Reputation: 468
Usually, I can disable an annoying warning by wrapping two pragma warning disable
statements around it. For instance:
#pragma warning disable IDE0060
public static int MultiplyByZero(int Number)
=> 0;
#pragma warning restore IDE0060
However, consider the following situation:
I have a file that uses many static classes all in the same namespace. They are very predictably named:
using static MyLib.Class0;
using static MyLib.Class1;
using static MyLib.Class2;
...
using static MyLib.Class9;
However, my class does not always use all these static classes. After one edit, it might only use Class0
, Class3
, and Class4
. After another, it might only use Class1, Class3, and Class6
. But I know that it is always going to use some of those classes.
When I attempt to save my file, Visual Studio naturally wants to refactor away all the unused using
s. I told it to do that, after all, and I do still want that to happen for other unused using
s, just not these.
Visual Studio did not provide the ID for removing unnecessary using
s, but I looked it up on Google, and found it was IDE0005
. So, as any good programmer would, I put that around my using
s:
#pragma warning disable IDE0005
using static MyLib.Class0;
using static MyLib.Class1;
using static MyLib.Class2;
...
using static MyLib.Class9;
#pragma warning restore IDE0005
Visual Studio agreed with me that the pragma
s were necessary, since it didn't lighten them as it usually does with unnecessary pragma
s. I assumed that meant it would do what I wanted. However, when I clicked save, my using
s disappeared anyway.
I looked at Intellisense's suggestions for other types of pragma
besides warning
. There was only checksum
, whose documentation looked rather scary, and unrelated to my problem.
How can I make Visual Studio keep specific using
statements?
To be clear, I am not looking for a file-wide or project-wide solution. There are other places where I would like that feature. I just need a way to mark a specific bit of code such that no using
s will be removed.
Edit:
As multiple users in the comments have noted, this is not default behavior for Visual Studio. I have "Remove unnecessary imports or usings" selected in Configure Code Cleanup. I didn't occur to me that not everyone did that. So I guess the question really is, "How can I disable Code Cleanup for a specific few lines of code".
Upvotes: 0
Views: 190
Reputation: 468
As users in the comments have stated, there does not currently exist such a feature in Visual Studio. Hopefully such a feature will be created in the future, but none exist yet.
Until then, I have worked around the problem by commenting out then unnecessary usings. Then, when they are necessary, I can simply uncomment them to use them.
Thanks anyway to those who tried. Happy coding.
Upvotes: 0