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.
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
.
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.
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");
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With