Ruslan Plastun
Ruslan Plastun

Reputation: 2254

Multiple Systems inside assemblies

When I look at assemblies in my references I can see multiple System namespaces:

enter image description here

So which one of them do I call when I have this code in my .cs file?

using System;   // <---------
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

How does this using algorithm finds appropriate namespace in these assemblies?

Upvotes: 1

Views: 56

Answers (2)

Farzan Hajian
Farzan Hajian

Reputation: 2019

Namespaces exist to package related types (classes, enums, ...) logically and to reduce the risk of name ambiguity. You can reference a couple assemblies that have a same namespace to your project.

Imagine you have referenced two assemblies and they both contain "namepsace2":

assembly1
    namespace1
    namespace2
            class1
            class2

assembly2
    namespace2
            class2
            class3
    namespace3
    namepsace4

When you use

using namepsace2;

you can access all types that reside inside "namespace2" in both assemblies without fully gualifiying their names:

    // you can use  
    class1 c1 = new class1();
    // instead of
    namepsace2.class1 c1 = new namepsace2.class1();

    // And also class3 can be used similarly

But "class2" causes broblem. You have to use its fully qualified name to tell the compiler excatly which "class2" you are interested in.

Upvotes: 2

madreflection
madreflection

Reputation: 4957

Namespaces effectively merge across all referenced assemblies. When you have using System;, you're importing types from the whole namespace, meaning that all types in that namespace in all referenced assemblies are made available.

A namespace doesn't even exist until there's a type in it.

If you wanted, you could define your own types in the System namespace, which makes them available whenever you have using System;. That's not to say that you should, only that it's possible.

Upvotes: 3

Related Questions