Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.Console resolving to incorrect namespace

Tags:

c#

I have a simple console app with the namespace of

something.service.console

The problem is when I try to use

Console.WriteLine("something");

I get compile error: The Type or namespace name "WriteLine" dos not exist in the namespace something.service.console.

So unless I use

System.Console.WriteLine("something");

The C# compiler is trying to resolve the method WriteLine to the incorrect namespace ("something.service.console"). In this scenario is it possible to force the compiler to resolve the Console.WriteLine to the correct namespace "System" (instead of renaming my namespace :))?

Thank you.

like image 335
J_PT Avatar asked Oct 17 '16 12:10

J_PT


3 Answers

The compiler will find the namespace something.service before it finds the namespace System so it will assume that

Console.WriteLine("something");

actually means

something.serviceConsole.WriteLine("something");

and hence your error.

Two possible solutions are to either fully qualify the namespace when you have issues like this:

System.Console.WriteLine("something");

or change the name of your namespace so it's not something.service.console but something.service.somethinglese.

like image 149
ChrisF Avatar answered Oct 15 '22 09:10

ChrisF


You could "force" it like this:

using SysConsole = System.Console; 

Now whenever you use Console in is refering to System.Console

public class Console
{
    private void Test()
    {
        SysConsole.WriteLine("something");
    }
}

Note: There really is nothing bad about using: System.Console.WriteLine() and you should avoid using classnames that already exist in the .NET Framework.

like image 41
Felix D. Avatar answered Oct 15 '22 09:10

Felix D.


Using a C# 6 feature "using static" you can change the code to in order to avoid the ambiguous name Console without cluttering the code.

This would make sense, if a lot of System.Console.WriteLine calls occur in the code.

using static System.Console;

namespace SomeNamespace.Console
{
    public class SomeClass
    {
        public void SomeMethod()
        {
            WriteLine("abc");
        }
    }
}
like image 34
Ralf Bönning Avatar answered Oct 15 '22 10:10

Ralf Bönning