How to make MSVS throw a warning for name conflicts instead of silently resolving?

Andrei Mirea 41 Reputation points
2023-09-06T17:59:09.26+00:00

In microsoft visual studio 2022, I have the C# code:

1. using UnityEngine;
2. namespace ns
3. {
4.  /*...*/
5.  public Color GetAlpha(){/*...*/}
6. }

The identifier *Color* at line 5 was interpreted by MSVS as UnityEngine.Color.

Now there is another file

/*...*/
namespace ns
{
 /*...*/
 public class Color {/*...*/}
 /*...*/
}

After some months I added the Color class into the second file as shown. MSVS silently changed *Color* in the first file at line 5 to refer to the class I've added. It messed things up and due to the confusion I had a bit of work till I traced down the culprit. And this was fortunate. Otherwise it might have been a silent bug.

My question: how can I make MSVS throw a warning and ask me to disambiguate the identifier in such cases, instead of silently resolving it by itself?

Thank you for your time.

Visual Studio
Visual Studio
A family of Microsoft suites of integrated development tools for building applications for Windows, the web and mobile devices.
4,888 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,648 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 61,731 Reputation points
    2023-09-06T18:30:30.38+00:00

    You can't. because its the same namespace, the using was not searched to discover the possible ambiguous reference. This is expected behavior as a class defined in the current namespace should be used instead of one defined in a using statement. It would be pretty painful if this wasn't true.

    you can use alias statement to force the namespace for Color.

    your best defense is careful naming, and better namespace partitioning:

    /*...*/
    namespace ns
    {
     /*...*/
     namespace ns.something
     {
         public class Color {/*...*/}
     }
     /*...*/
    }
    

    or parent classes

    namespace ns
    {
      public static class Something
      {
         public class Color {/*...*/}
        /*...*/
      }
    }