Reputation: 63
I'm new to C# and I don't fully understand what a namespace is, and what the using-keyword does. I'd appreciate it if someone could explain the difference. From my guess, using
is similar to #include
in C++.
If that's the case, what is a namespace for? The only exposure I've had to namespaces in C++, was when using using namespace std;
, which just allowed me to forgo the std::
in my function calls.
Upvotes: 1
Views: 3748
Reputation: 3018
namespace
: A group of related classes, interfaces, and other types into a single unit. It's a logical grouping of related types.
using
: Mostly used to import namespaces.
Example: using System;
It can also used for resource management like ensure that disposable resources, such as files or database connections, are properly disposed of when they go out of scope.
Example: using (FileStream fileStream = new FileStream()) { }
This ensures that the file stream is closed and disposed of properly, even if an exception is thrown, to prevent resource leaks.
Upvotes: 2
Reputation: 1
Quick short answer -
namespace - is a collection of classes that you are naming and filling with classes yourself
using - brings in a namespace(collection of classes) to be used
For a cleaner understanding of the parts of a C# program - https://www.tutorialspoint.com/What-are-the-main-parts-of-a-Chash-program
Upvotes: 0
Reputation: 39
in my understanding,
using: is kind of import in Javascript. Means, using some code from another file where the code is exported.
namespace: is kind of export in Javascript. Means, make this code to available for another file.
Upvotes: -1
Reputation: 348
The namespace
-statement declares a namespace of your own; A set of "bundled classes" if you like. You can have very different classes in a name space, and you can also create sub-namespaces.
Using the namespace
statement will therefor, implicitly make sure you can access other classes in the same namespace. You do not need to make explicit references within the same namespace.
Read more on namespaces in C# here.
The using
directive is used to use a namespace in your code, without explicitly referencing to a namespace. This is of course useful when using a namespace more than once in a class. The directive does not change the state or status of the class, as the namespace
statement does.
Read more on the using directive in C# here.
There is also much more things you can do with the using
keyword...
Upvotes: 2
Reputation: 95
you are almost correct.
To find out more about namespace and using refer here
Since you are new to C# i recommend you to go through the microsoft c# and .Net documentation if you have any doubts. Hope this helps :)
Upvotes: -1