What is the difference between a class library and a namespace?
Asked Answered
E

3

10

What is the actual difference between class library and a namespace? I know both are used to group together classes, namespace etc. Can anyone tell in which scenario should I use a class library and when to go for creating a new namespace.

Efflorescence answered 11/7, 2012 at 7:1 Comment(0)
D
11

Namespaces provide a notional separation for classes, class libraries provide a physical separation (in windows think a standalone dll).

Class libraries are useful for when you want to wrap up functionality that can be shared with other projects.

Imagine creating a windows application where you split the UI and the implementation classes (class library) into 2 different projects. Then you find you need to have a web version of the same thing. You can just import the class library you created from the windows application and you have all your implementation available to you and just focus on the web UI.

If you'd created the whole windows app in one project using namespaces to seperate them, doing that would be tricky & messy. (ever tried importing an exe?)

It is worth pointing out that class libraries will themselves likely use namespaces to provide further notional separation to the classes within them

Doublecheck answered 11/7, 2012 at 7:26 Comment(0)
T
5

The purpose of namespaces is to avoid name collisions. Namespace should be used when your have several hundreds of classes. Other indicator - when your code is used by somebody else and your names may collide with names in the user code.

Other important difference is that class is always a data type. You can define variables with this type. Namespace is not a type. You cannot define vars with the namespace.

Trilobite answered 11/7, 2012 at 7:3 Comment(1)
Then you need to be more specific in what language are you using.Trilobite
L
0

A class library is a package of types (class, struct, and so on) that are compiled into a deployable unit (DLL(Dynamic Link Library) files). The purpose of it is to make code reusable across multiple projects.

On the other hand, a namespace has a broader meaning than a class library. It can be used to specify that the types defined in this file are part of this namespace. The main aim of it is to organize related types into a logical grouping.

To visualize the difference, you can think of a namespace, a file room consisting of many folders. And a class library is a folder that includes many files (class, struct, and so on).

Limpet answered 12/5, 2023 at 14:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.