I'm new to C# and I can't seem to find any info on this so I will ask it here.
Do classes in namespaces have to ever be declared?
using System;
public class myprogram
{
void main()
{
// The console class does not have to be declared?
Console.WriteLine("Hello World");
}
}
If I'm not using a namespace then I have to declare a class
class mathstuff
{
private int numberone = 2;
private int numbertwo = 3;
public int addhere()
{
return numberone + numbertwo;
}
using System;
public class myprogram
{
void main()
{
// the class here needs to be declared.
mathstuff mymath = new mathstuff();
Console.WriteLine(mymath.addhere());
}
}
Am I understanding this correctly?
A namespace is simply a way to make clear in which context the class is living in. Think of your own name, Ralph. We have many Ralphs in this world, but one of that is you. An extra way to get rid of the ambiguity is to add your surname. So that if we have 2 Ralphs, we have a bigger chance of talking about you.
The same works for classes. If you define class
AClass
and you would have the need of define another classAClass
there would be no way to distinguish between the two. A namespace would be that 'surname'. A way of having to classes, but still able to distinguish between the two different classes, with the same name.To answer your question, it has nothing to do with "not having to declare". It would only be easier to write code.
For example:
Because of the
using System;
you don't have to declare the namespace ofConsole
. There is only oneConsole
available, which lives in theSystem
namespace. If you wouldn't declare yourusing System;
namespace then you'd need to explain whereConsole
can be found. Like this.From MSDN:
For more info check MSDN for namespace.
I think what you mean is "can you declare a class without a namespace?". Yes you can, it's referred to as the
global
namespace.However, this is very bad practice, and you should never do this in a production application.