SlideShare une entreprise Scribd logo
1  sur  10
Télécharger pour lire hors ligne
2
Namespaces
Normally, students have an implicit trust in their teachers. For they know that if the blind lead the
blind, both shall fall into the ditch. However, our philosophy is that a good teacher has to be an
even better liar!!

In accordance with this belief, initially we told you that WriteLine is the name of a function. Then
we told you that the name is not WriteLine, it is System.Console.WriteLine. But even that's not
true.

Now comes the moment of truth.

Console is actually the name of a class. Yes, trust us! There is no crying wolf here. The class
Console has a function called WriteLine. Hence the name now becomes Console.WriteLine.
However, that leaves out the word System. Now what does System mean?

Well, a number of functions like WriteLine are available in C#. Some functions will let you print,
some will enable writing of data to disk and others will let you create graphics. The problem that
we are posed with is - how does one remember which function satisfies what purpose?
Wouldn't it make sense if we logically grouped similar functions together? So, Microsoft thought
that all functions that can write to the screen could be made part of one class. All functions that
let you work with pictures could be part of another class. But even then, you will have too many
functions in one class. So they thought of having a single higher logical group. Such that all the
functions that have anything to do with the screen, i.e. whether you are drawing pictures or
writing text, be grouped once again into a higher body. Thus all classes that deal with interacting
with a database could go into a group called Data.

The second problem that we are posed with is that of name clashes. What do we mean by that?
Now, nothing can stop me from creating my own class called Console and include a function
called WriteLine in it. But how will C# know which Console am I referring to? The one that we
created ourselves, or the one that Microsoft has already created. In order to resolve these
problems Microsoft decided to take classes and put them into namespaces. What is a namespace?
It is simply a word. Thus we can logically group everything as per namespaces.

From the above explanation you would have by now guessed that System is nothing but a
namespace. The following programs will help make this concept crystal clear.

        a.cs
        class zzz
{
       static void Main()
       {
       yyy.abc();
       abc();
       zzz.abc();
       }
       public static void abc()
       {
       System.Console.WriteLine(quot;abc in zzz quot;);
       }
       }
       namespace vijay
       {
       class yyy
       {
       public static void abc()
       {
       System.Console.WriteLine(quot;abcquot;);
       }
       }
       }

       Compiler Error
       a.cs(5,1): error CS0246: The type or namespace name 'yyy' could not be found (are you
       missing a using directive or an assembly reference?)

In the above program, the only change that we have made is that we have now included the class
yyy in a namespace called vijay. On doing so you will realize that the same program that worked
earlier doesn't work anymore. This is because yyy is put in a namespace vijay.

A namespace is nothing but a word with an open and close brace. The entire class is enclosed
within the namespace. If you want to access a function belonging to class yyy from another class
then the only way to do so is by saying vijay.yyy.abc(); Thus you specify the namespace first,
then the name of the class followed by the name of the function, each of them separated by dots.
Thus like Urdu, we read anything from the right and not the left. We start with the name of a
function, then the name of the class and whatever is left is the namespace.

Here zzz has not been given a namespace. If you don't specify a namespace then by default the
class is included in a global namespace. Now change yyy.abc(); to vijay.yyy.abc() and watch the
error disappear.

       a.cs
       class zzz
       {
       static void Main()
       {
       vijay.yyy.abc();
       abc();
       zzz.abc();
       }
       public static void abc()
       {
System.Console.WriteLine(quot;abc in zzz quot;);
        }
        }
        namespace vijay
        {
        class yyy
        {
        public static void abc()
        {
        System.Console.WriteLine(quot;abcquot;);
        }
        }
        }

        Output
        abc
        abc in zzz
        abc in zzz

We bet your faces are now beaming! Seems like the secret of happiness is not in doing what one
likes to do but in liking what one has to do. We had to get rid of the error which we have
succeeded in doing. The error has disappeared; the program executes as advertised and it
generates the same output as it did previously.

Thus all the classes and functions created by Vijay can be included in a namespace called vijay. If
Sonal creates a namespace by her name then she can include all the functions and classes created
by her in the namespace sonal. Thus there will be no name clashes at all. These namespaces that
are created by us are called user-defined namespaces whereas System is a pre-defined namespace.
Thus System is a namespace in which a class called Console was created, which contained a
function called WriteLine.

Thus the namespace concept allows us to create logical groups. So all xml related classes can be
in a namespace called xml, web can be in a web namespace and so on and so forth.

But the only problem now is that when you start writing code you have to specify the namespace
first, then the class name followed by the function name. Well, everything is available but for a
price! Our consolation is that it is a very small price to pay.

        a.cs
        namespace mukhi
        {
        class zzz
        {
        static void Main()
        {
        vijay.yyy.abc();
        abc();
        zzz.abc();
        mukhi.zzz.abc();
        }
        public static void abc()
        {
System.Console.WriteLine(quot;abc in zzz quot;);
        }
        }
        }
        namespace vijay
        {
        class yyy
        {
        public static void abc()
        {
        System.Console.WriteLine(quot;abcquot;);
        }
        }
        }
        Output
        abc
        abc in zzz
        abc in zzz
        abc in zzz

In the above program, we have two classes zzz and yyy. The class zzz is included in a namespace
called mukhi and the class yyy is included in a namespace called vijay.

So when we say abc(); in Main, Main is in zzz, so you are actually writing mukhi.zzz.abc(); This
is because C# will automatically expand it since the function abc is available within the same
class. Hence it is at your discretion as to how you want to write it. You can say abc(), zzz.abc() or
mukhi.zzz.abc(); finally they all expand to namespace.classname.function name. C# adds the
name of the namespace and the name of the class even if you do not specifically write it. The
concept of namespaces is not very difficult to understand. It allows for a hierarchical grouping of
classes. It tells us which classes are logically grouped. It also avoids classes from having the same
name.

        a.cs
        class zzz
        {
        static void Main()
        {
        Console.WriteLine(quot;abc in zzz quot;);
        }
        }

        Compiler Error
        a.cs(5,1): error CS0246: The type or namespace name 'Console' could not be found (are
        you missing a using directive or an assembly reference?)

If we do not enclose our class in a namespace, it becomes part and parcel of the global namespace
‘ ‘. This namespace does not contain a class called Console. We had mentioned earlier that the
class Console is contained in the namespace System. We do not want to preface the Console class
with the namespace System each and every time. The only reason being that our fingers will wear
out typing the word System over and over again. So C# lets us use a shorthand by means of which
we avoid the pain of having to keep on writing the name of a namespace over and over again.

        a.cs
using System;
        class zzz
        {
        static void Main()
        {
        Console.WriteLine(quot;abc in zzz quot;);
        }
        }

        Output
        abc in zzz

The secret here is not in doing great things, but doing a small thing in a great way. We get no
error simply by employing the word using which is part of the C# language. All that using does is
whenever it sees only the name of a class, it goes and adds (in this case) the word System. Thus
we do not have to write the word System over and over again. This works the way shorthand
does.

        a.cs
        using System;
        class zzz
        {
        static void Main()
        {
        yyy.abc();
        }
        }
        namespace vijay
        {
        class yyy
        {
        public static void abc()
        {
        Console.WriteLine(quot;abcquot;);
        }
        }
        }

        Compiler Error
        a.cs(6,1): error CS0246: The type or namespace name 'yyy' could not be found (are you
        missing a using directive or an assembly reference?)

Now we get an error for yyy and not for Console as the yyy class belongs to the vijay namespace
and not the global namespace. Because of the using keyword, C# adds the namespace System to
yyy yielding System.yyy.abc and realizes that System does not contain a class called yyy. Hence
the error.

        a.cs
        using System;
        using vijay;
        class zzz {
        static void Main()
        {
yyy.abc();
        }
        }
        namespace vijay
        {
        class yyy
        {
        public static void abc()
        {
        Console.WriteLine(quot;abcquot;);
        }
        }
        }
        Output
        abc

The error vanishes as C# first tries System.yyy.abc gets an error, then tries vijay.yyy.abc and is
successful. Thus by having two using's we do not have to write the namespaces vijay or System
ever again.

        a.cs
        using System;
        using mukhi;
        using vijay;
        namespace mukhi
        {
        class zzz
        {
        static void Main()
        {
        yyy.abc();
        abc();
        zzz.abc();
        zzz.abc();
        }
        public static void abc()
        {
        System.Console.WriteLine(quot;abc in zzz quot;);
        }
        }
        }
        namespace vijay
        {
        class yyy
        {
        public static void abc()
        {
        System.Console.WriteLine(quot;abcquot;);
        }
        }
        }

        Output
abc
        abc in zzz
        abc in zzz
        abc in zzz

We can have as many using's as we like and the compiler will try each one in turn. If none of
them match we will receive an error. In this case it will try 3 times with System, mukhi and vijay
and if none match, you will get an error.

        a.cs
        using System.Console;
        class zzz
        {
        static void Main()
        {
        WriteLine(quot;abc in zzz quot;);
        }
        }

        Compiler Error
        a.cs(1,7): error CS0138: A using namespace directive can only be applied to
        namespaces; 'System.Console' is a class not a namespace

After the word using you can only write the name of a namespace. System.Console is a
namespace class combination which is not allowed.

Building Hierarchy
In C# you organize classes using namespaces. Now let's discover the extent we can go to as far as
organizing classes.

        a.cs
        class zzz
        {
        static void Main()
        {
        mukhi.vijay.yyy.abc();
        }
        }
        namespace mukhi
        {
        namespace vijay
        {
        class yyy {
        public static void abc()
        {
        System.Console.WriteLine(quot;abcquot;);
        }
        }
        }
        }

        Output
abc

In this program we have a namespace within a namespace i.e. within the namespace mukhi we
have another namespace vijay. Thus namespaces are 'hierarchical'. If you want to access the
function abc in yyy you have to specify it in the form- namespace.classname.functionname. So,
the qualified name is now mukhi.vijay.yyy.abc(); Once the function is called, WriteLine will
display 'abc'.

In order to differentiate between the various names separated by dots, always read backwards.
Reading backwards, the first is the function name then the class name and the names thereafter
will all be namespaces.

Alternatively, you can directly specify the namespace as mukhi.vijay, as we have done below.
This program generates the same output as previously, it prints abc.

        a.cs
        class zzz
        {
        static void Main()
        {
        mukhi.vijay.yyy.abc();
        }
        }
        namespace mukhi.vijay
        {
        class yyy
        {
        public static void abc()
        {
        System.Console.WriteLine(quot;abcquot;);
        }
        }
        }

        Output
        abc

Here we have a single namespace by the name mukhi.vijay. The name mukhi.vijay is actually a
shortcut for defining a namespace named mukhi that contains a namespace named vijay. In this
program, we have only two namespaces. But you can expand it further to include a number of
namespaces depending upon the level of hierarchy required by your program.

We can liken this to an organization. Let's consider mukhi to be the name of the company. Within
that you have a sub-company or a division called vijay, which creates it own classes. As such the
level of hierarchy can be expanded.

Before you understand the next program let's address a simple question. Why do you use classes?
Classes are used because they offer a large number of functions. You don't use classes because of
the variables that you can create within them; you use classes for the functions that they provide.
Remember, you call a function using the form -namespace.classname.functionname.
File Operations
a.cs
        class zzz
        {
        static void Main()
        {
        File.Copy(quot;c:csharpa.txtquot;,quot;c:csharpb.txtquot;,true);
        }
        }

        Compiler Error
        a.cs(5,1): error CS0246: The type or namespace name 'File' could not be found (are you
        missing a using directive or an assembly reference?)

Our next program will enlighten you on something most sought after - The art of Copying. Ah!
Finally something of interest!

This program introduces the 'Copy' function. It allows you to duplicate a file. File is a class and it
has a function called Copy, which is static.

The first parameter 'a.txt' is the source file i.e. the file, which we want to duplicate. The second
parameter 'b.txt' is the destination file i.e. the file that we want to copy to. Note that you must
specify the entire path for the file name. The last parameter 'true' implies that if the file exists then
it will be overwritten. If the file does not exist it will be created and contents of the source file
will be copied onto it.

And just when you thought you had mastered the art of copying the program returns with an error
message. The error says C# does not know what File.Copy is. The problem is that the name of the
namespace is System.IO. So you have to specify the namespace too.

Add the namespace and execute the program.


        a.cs
        class zzz
        {
        static void Main()
        {
        System.IO.File.Copy(quot;c:csharpa.txtquot;,quot;c:csharpb.txtquot;,true);
        }
        }

The program does not generate any compilation errors. Create a file called a.txt with some text
before you run this program. Execute this program and then open the file 'b.txt'. Finally, the task
has been accomplished! You now have the contents of a.txt copied into b.txt.

Our next program introduces another function called 'Delete'.

        a.cs
        class zzz
        {
        static void Main()
        {
System.IO.File.Delete(quot;c:csharpa.txtquot;);
       }
       }

The above program takes the name of a file as the parameter. This function will remove the file
specified from disk. Give the dir command at the command prompt and you will find that the file
has been deleted.

Every language will offer you millions of such functions like copy and delete. These
functions were always available, but C# has gone one step further and made these
functions a part of a Class. They are now part of a Namespace. Hence it becomes easier
to categorize functions. It is but a question of detail whether you should or should not
categorize them.

Contenu connexe

En vedette

01 Pohledy Mrazivá Zima
01 Pohledy Mrazivá Zima01 Pohledy Mrazivá Zima
01 Pohledy Mrazivá Zimajedlickak01
 
Csharp In Detail Part2
Csharp In Detail Part2Csharp In Detail Part2
Csharp In Detail Part2Mohamed Krar
 
Proyecto On Site
Proyecto On SiteProyecto On Site
Proyecto On Siteguest9796c0
 
La Urgencia Por Destruir El Territorio Regional
La Urgencia Por Destruir El Territorio RegionalLa Urgencia Por Destruir El Territorio Regional
La Urgencia Por Destruir El Territorio RegionalRaúl Pleguezuelo
 
Árvores de minha infância
Árvores de minha infânciaÁrvores de minha infância
Árvores de minha infânciaVera Regina
 
Resumen Radio Digital (Dab)
Resumen Radio Digital (Dab)Resumen Radio Digital (Dab)
Resumen Radio Digital (Dab)fgcalvo
 
01 Pohledy OhromujíCí
01 Pohledy OhromujíCí01 Pohledy OhromujíCí
01 Pohledy OhromujíCíjedlickak01
 
01 Pohledy KráSná Modrá Planeta
01 Pohledy KráSná Modrá Planeta01 Pohledy KráSná Modrá Planeta
01 Pohledy KráSná Modrá Planetajedlickak01
 
Las Criadas
Las CriadasLas Criadas
Las Criadasviola
 
01 Pohledy Evropa
01 Pohledy Evropa01 Pohledy Evropa
01 Pohledy Evropajedlickak01
 
01 Pohledy Nejlepší Pohledy Hor
01 Pohledy Nejlepší Pohledy Hor01 Pohledy Nejlepší Pohledy Hor
01 Pohledy Nejlepší Pohledy Horjedlickak01
 

En vedette (18)

01 Pohledy Mrazivá Zima
01 Pohledy Mrazivá Zima01 Pohledy Mrazivá Zima
01 Pohledy Mrazivá Zima
 
Csharp In Detail Part2
Csharp In Detail Part2Csharp In Detail Part2
Csharp In Detail Part2
 
Proyecto On Site
Proyecto On SiteProyecto On Site
Proyecto On Site
 
Amor
AmorAmor
Amor
 
La Urgencia Por Destruir El Territorio Regional
La Urgencia Por Destruir El Territorio RegionalLa Urgencia Por Destruir El Territorio Regional
La Urgencia Por Destruir El Territorio Regional
 
B L O G’ S
B L O G’ SB L O G’ S
B L O G’ S
 
Circo
CircoCirco
Circo
 
Desem Ki
Desem KiDesem Ki
Desem Ki
 
Dbz
DbzDbz
Dbz
 
Árvores de minha infância
Árvores de minha infânciaÁrvores de minha infância
Árvores de minha infância
 
Resumen Radio Digital (Dab)
Resumen Radio Digital (Dab)Resumen Radio Digital (Dab)
Resumen Radio Digital (Dab)
 
01 Pohledy OhromujíCí
01 Pohledy OhromujíCí01 Pohledy OhromujíCí
01 Pohledy OhromujíCí
 
Csharp_Contents
Csharp_ContentsCsharp_Contents
Csharp_Contents
 
01 Pohledy KráSná Modrá Planeta
01 Pohledy KráSná Modrá Planeta01 Pohledy KráSná Modrá Planeta
01 Pohledy KráSná Modrá Planeta
 
Las Criadas
Las CriadasLas Criadas
Las Criadas
 
01 Pohledy Evropa
01 Pohledy Evropa01 Pohledy Evropa
01 Pohledy Evropa
 
01 Pohledy Nejlepší Pohledy Hor
01 Pohledy Nejlepší Pohledy Hor01 Pohledy Nejlepší Pohledy Hor
01 Pohledy Nejlepší Pohledy Hor
 
Onassis
OnassisOnassis
Onassis
 

Similaire à Namespaces in C

Similaire à Namespaces in C (20)

Csharp_Chap03
Csharp_Chap03Csharp_Chap03
Csharp_Chap03
 
Csharp_Chap04
Csharp_Chap04Csharp_Chap04
Csharp_Chap04
 
Csharp_Chap06
Csharp_Chap06Csharp_Chap06
Csharp_Chap06
 
Csharp_Chap08
Csharp_Chap08Csharp_Chap08
Csharp_Chap08
 
Wade Not in Unknown Waters. Part Four.
Wade Not in Unknown Waters. Part Four.Wade Not in Unknown Waters. Part Four.
Wade Not in Unknown Waters. Part Four.
 
Java concurrency questions and answers
Java concurrency questions and answers Java concurrency questions and answers
Java concurrency questions and answers
 
06 abstract-classes
06 abstract-classes06 abstract-classes
06 abstract-classes
 
LEARN C#
LEARN C#LEARN C#
LEARN C#
 
Javantura v3 - ES6 – Future Is Now – Nenad Pečanac
Javantura v3 - ES6 – Future Is Now – Nenad PečanacJavantura v3 - ES6 – Future Is Now – Nenad Pečanac
Javantura v3 - ES6 – Future Is Now – Nenad Pečanac
 
Inheritance
InheritanceInheritance
Inheritance
 
Synapseindia dot net development
Synapseindia dot net developmentSynapseindia dot net development
Synapseindia dot net development
 
06 abstract-classes
06 abstract-classes06 abstract-classes
06 abstract-classes
 
Diving in OOP (Day 2): Polymorphism and Inheritance (Inheritance)
Diving in OOP (Day 2): Polymorphism and Inheritance (Inheritance)Diving in OOP (Day 2): Polymorphism and Inheritance (Inheritance)
Diving in OOP (Day 2): Polymorphism and Inheritance (Inheritance)
 
Wade Not in Unknown Waters. Part Four.
Wade Not in Unknown Waters. Part Four.Wade Not in Unknown Waters. Part Four.
Wade Not in Unknown Waters. Part Four.
 
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sirAdvanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
 
Advance java kvr -satya
Advance java  kvr -satyaAdvance java  kvr -satya
Advance java kvr -satya
 
Adv kvr -satya
Adv  kvr -satyaAdv  kvr -satya
Adv kvr -satya
 
Unit2 java
Unit2 javaUnit2 java
Unit2 java
 
Chapter 9 Abstract Class
Chapter 9 Abstract ClassChapter 9 Abstract Class
Chapter 9 Abstract Class
 
E5
E5E5
E5
 

Plus de Mohamed Krar

Plus de Mohamed Krar (10)

Csharp_Chap14
Csharp_Chap14Csharp_Chap14
Csharp_Chap14
 
Csharp_Chap15
Csharp_Chap15Csharp_Chap15
Csharp_Chap15
 
Csharp_Intro
Csharp_IntroCsharp_Intro
Csharp_Intro
 
Csharp_Chap12
Csharp_Chap12Csharp_Chap12
Csharp_Chap12
 
Csharp_Chap11
Csharp_Chap11Csharp_Chap11
Csharp_Chap11
 
Csharp_Chap07
Csharp_Chap07Csharp_Chap07
Csharp_Chap07
 
Csharp_Chap10
Csharp_Chap10Csharp_Chap10
Csharp_Chap10
 
Csharp_Chap09
Csharp_Chap09Csharp_Chap09
Csharp_Chap09
 
Csharp_Chap05
Csharp_Chap05Csharp_Chap05
Csharp_Chap05
 
Csharp_Chap01
Csharp_Chap01Csharp_Chap01
Csharp_Chap01
 

Dernier

Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Visualising and forecasting stocks using Dash
Visualising and forecasting stocks using DashVisualising and forecasting stocks using Dash
Visualising and forecasting stocks using Dashnarutouzumaki53779
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 

Dernier (20)

Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Visualising and forecasting stocks using Dash
Visualising and forecasting stocks using DashVisualising and forecasting stocks using Dash
Visualising and forecasting stocks using Dash
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 

Namespaces in C

  • 1. 2 Namespaces Normally, students have an implicit trust in their teachers. For they know that if the blind lead the blind, both shall fall into the ditch. However, our philosophy is that a good teacher has to be an even better liar!! In accordance with this belief, initially we told you that WriteLine is the name of a function. Then we told you that the name is not WriteLine, it is System.Console.WriteLine. But even that's not true. Now comes the moment of truth. Console is actually the name of a class. Yes, trust us! There is no crying wolf here. The class Console has a function called WriteLine. Hence the name now becomes Console.WriteLine. However, that leaves out the word System. Now what does System mean? Well, a number of functions like WriteLine are available in C#. Some functions will let you print, some will enable writing of data to disk and others will let you create graphics. The problem that we are posed with is - how does one remember which function satisfies what purpose? Wouldn't it make sense if we logically grouped similar functions together? So, Microsoft thought that all functions that can write to the screen could be made part of one class. All functions that let you work with pictures could be part of another class. But even then, you will have too many functions in one class. So they thought of having a single higher logical group. Such that all the functions that have anything to do with the screen, i.e. whether you are drawing pictures or writing text, be grouped once again into a higher body. Thus all classes that deal with interacting with a database could go into a group called Data. The second problem that we are posed with is that of name clashes. What do we mean by that? Now, nothing can stop me from creating my own class called Console and include a function called WriteLine in it. But how will C# know which Console am I referring to? The one that we created ourselves, or the one that Microsoft has already created. In order to resolve these problems Microsoft decided to take classes and put them into namespaces. What is a namespace? It is simply a word. Thus we can logically group everything as per namespaces. From the above explanation you would have by now guessed that System is nothing but a namespace. The following programs will help make this concept crystal clear. a.cs class zzz
  • 2. { static void Main() { yyy.abc(); abc(); zzz.abc(); } public static void abc() { System.Console.WriteLine(quot;abc in zzz quot;); } } namespace vijay { class yyy { public static void abc() { System.Console.WriteLine(quot;abcquot;); } } } Compiler Error a.cs(5,1): error CS0246: The type or namespace name 'yyy' could not be found (are you missing a using directive or an assembly reference?) In the above program, the only change that we have made is that we have now included the class yyy in a namespace called vijay. On doing so you will realize that the same program that worked earlier doesn't work anymore. This is because yyy is put in a namespace vijay. A namespace is nothing but a word with an open and close brace. The entire class is enclosed within the namespace. If you want to access a function belonging to class yyy from another class then the only way to do so is by saying vijay.yyy.abc(); Thus you specify the namespace first, then the name of the class followed by the name of the function, each of them separated by dots. Thus like Urdu, we read anything from the right and not the left. We start with the name of a function, then the name of the class and whatever is left is the namespace. Here zzz has not been given a namespace. If you don't specify a namespace then by default the class is included in a global namespace. Now change yyy.abc(); to vijay.yyy.abc() and watch the error disappear. a.cs class zzz { static void Main() { vijay.yyy.abc(); abc(); zzz.abc(); } public static void abc() {
  • 3. System.Console.WriteLine(quot;abc in zzz quot;); } } namespace vijay { class yyy { public static void abc() { System.Console.WriteLine(quot;abcquot;); } } } Output abc abc in zzz abc in zzz We bet your faces are now beaming! Seems like the secret of happiness is not in doing what one likes to do but in liking what one has to do. We had to get rid of the error which we have succeeded in doing. The error has disappeared; the program executes as advertised and it generates the same output as it did previously. Thus all the classes and functions created by Vijay can be included in a namespace called vijay. If Sonal creates a namespace by her name then she can include all the functions and classes created by her in the namespace sonal. Thus there will be no name clashes at all. These namespaces that are created by us are called user-defined namespaces whereas System is a pre-defined namespace. Thus System is a namespace in which a class called Console was created, which contained a function called WriteLine. Thus the namespace concept allows us to create logical groups. So all xml related classes can be in a namespace called xml, web can be in a web namespace and so on and so forth. But the only problem now is that when you start writing code you have to specify the namespace first, then the class name followed by the function name. Well, everything is available but for a price! Our consolation is that it is a very small price to pay. a.cs namespace mukhi { class zzz { static void Main() { vijay.yyy.abc(); abc(); zzz.abc(); mukhi.zzz.abc(); } public static void abc() {
  • 4. System.Console.WriteLine(quot;abc in zzz quot;); } } } namespace vijay { class yyy { public static void abc() { System.Console.WriteLine(quot;abcquot;); } } } Output abc abc in zzz abc in zzz abc in zzz In the above program, we have two classes zzz and yyy. The class zzz is included in a namespace called mukhi and the class yyy is included in a namespace called vijay. So when we say abc(); in Main, Main is in zzz, so you are actually writing mukhi.zzz.abc(); This is because C# will automatically expand it since the function abc is available within the same class. Hence it is at your discretion as to how you want to write it. You can say abc(), zzz.abc() or mukhi.zzz.abc(); finally they all expand to namespace.classname.function name. C# adds the name of the namespace and the name of the class even if you do not specifically write it. The concept of namespaces is not very difficult to understand. It allows for a hierarchical grouping of classes. It tells us which classes are logically grouped. It also avoids classes from having the same name. a.cs class zzz { static void Main() { Console.WriteLine(quot;abc in zzz quot;); } } Compiler Error a.cs(5,1): error CS0246: The type or namespace name 'Console' could not be found (are you missing a using directive or an assembly reference?) If we do not enclose our class in a namespace, it becomes part and parcel of the global namespace ‘ ‘. This namespace does not contain a class called Console. We had mentioned earlier that the class Console is contained in the namespace System. We do not want to preface the Console class with the namespace System each and every time. The only reason being that our fingers will wear out typing the word System over and over again. So C# lets us use a shorthand by means of which we avoid the pain of having to keep on writing the name of a namespace over and over again. a.cs
  • 5. using System; class zzz { static void Main() { Console.WriteLine(quot;abc in zzz quot;); } } Output abc in zzz The secret here is not in doing great things, but doing a small thing in a great way. We get no error simply by employing the word using which is part of the C# language. All that using does is whenever it sees only the name of a class, it goes and adds (in this case) the word System. Thus we do not have to write the word System over and over again. This works the way shorthand does. a.cs using System; class zzz { static void Main() { yyy.abc(); } } namespace vijay { class yyy { public static void abc() { Console.WriteLine(quot;abcquot;); } } } Compiler Error a.cs(6,1): error CS0246: The type or namespace name 'yyy' could not be found (are you missing a using directive or an assembly reference?) Now we get an error for yyy and not for Console as the yyy class belongs to the vijay namespace and not the global namespace. Because of the using keyword, C# adds the namespace System to yyy yielding System.yyy.abc and realizes that System does not contain a class called yyy. Hence the error. a.cs using System; using vijay; class zzz { static void Main() {
  • 6. yyy.abc(); } } namespace vijay { class yyy { public static void abc() { Console.WriteLine(quot;abcquot;); } } } Output abc The error vanishes as C# first tries System.yyy.abc gets an error, then tries vijay.yyy.abc and is successful. Thus by having two using's we do not have to write the namespaces vijay or System ever again. a.cs using System; using mukhi; using vijay; namespace mukhi { class zzz { static void Main() { yyy.abc(); abc(); zzz.abc(); zzz.abc(); } public static void abc() { System.Console.WriteLine(quot;abc in zzz quot;); } } } namespace vijay { class yyy { public static void abc() { System.Console.WriteLine(quot;abcquot;); } } } Output
  • 7. abc abc in zzz abc in zzz abc in zzz We can have as many using's as we like and the compiler will try each one in turn. If none of them match we will receive an error. In this case it will try 3 times with System, mukhi and vijay and if none match, you will get an error. a.cs using System.Console; class zzz { static void Main() { WriteLine(quot;abc in zzz quot;); } } Compiler Error a.cs(1,7): error CS0138: A using namespace directive can only be applied to namespaces; 'System.Console' is a class not a namespace After the word using you can only write the name of a namespace. System.Console is a namespace class combination which is not allowed. Building Hierarchy In C# you organize classes using namespaces. Now let's discover the extent we can go to as far as organizing classes. a.cs class zzz { static void Main() { mukhi.vijay.yyy.abc(); } } namespace mukhi { namespace vijay { class yyy { public static void abc() { System.Console.WriteLine(quot;abcquot;); } } } } Output
  • 8. abc In this program we have a namespace within a namespace i.e. within the namespace mukhi we have another namespace vijay. Thus namespaces are 'hierarchical'. If you want to access the function abc in yyy you have to specify it in the form- namespace.classname.functionname. So, the qualified name is now mukhi.vijay.yyy.abc(); Once the function is called, WriteLine will display 'abc'. In order to differentiate between the various names separated by dots, always read backwards. Reading backwards, the first is the function name then the class name and the names thereafter will all be namespaces. Alternatively, you can directly specify the namespace as mukhi.vijay, as we have done below. This program generates the same output as previously, it prints abc. a.cs class zzz { static void Main() { mukhi.vijay.yyy.abc(); } } namespace mukhi.vijay { class yyy { public static void abc() { System.Console.WriteLine(quot;abcquot;); } } } Output abc Here we have a single namespace by the name mukhi.vijay. The name mukhi.vijay is actually a shortcut for defining a namespace named mukhi that contains a namespace named vijay. In this program, we have only two namespaces. But you can expand it further to include a number of namespaces depending upon the level of hierarchy required by your program. We can liken this to an organization. Let's consider mukhi to be the name of the company. Within that you have a sub-company or a division called vijay, which creates it own classes. As such the level of hierarchy can be expanded. Before you understand the next program let's address a simple question. Why do you use classes? Classes are used because they offer a large number of functions. You don't use classes because of the variables that you can create within them; you use classes for the functions that they provide. Remember, you call a function using the form -namespace.classname.functionname. File Operations
  • 9. a.cs class zzz { static void Main() { File.Copy(quot;c:csharpa.txtquot;,quot;c:csharpb.txtquot;,true); } } Compiler Error a.cs(5,1): error CS0246: The type or namespace name 'File' could not be found (are you missing a using directive or an assembly reference?) Our next program will enlighten you on something most sought after - The art of Copying. Ah! Finally something of interest! This program introduces the 'Copy' function. It allows you to duplicate a file. File is a class and it has a function called Copy, which is static. The first parameter 'a.txt' is the source file i.e. the file, which we want to duplicate. The second parameter 'b.txt' is the destination file i.e. the file that we want to copy to. Note that you must specify the entire path for the file name. The last parameter 'true' implies that if the file exists then it will be overwritten. If the file does not exist it will be created and contents of the source file will be copied onto it. And just when you thought you had mastered the art of copying the program returns with an error message. The error says C# does not know what File.Copy is. The problem is that the name of the namespace is System.IO. So you have to specify the namespace too. Add the namespace and execute the program. a.cs class zzz { static void Main() { System.IO.File.Copy(quot;c:csharpa.txtquot;,quot;c:csharpb.txtquot;,true); } } The program does not generate any compilation errors. Create a file called a.txt with some text before you run this program. Execute this program and then open the file 'b.txt'. Finally, the task has been accomplished! You now have the contents of a.txt copied into b.txt. Our next program introduces another function called 'Delete'. a.cs class zzz { static void Main() {
  • 10. System.IO.File.Delete(quot;c:csharpa.txtquot;); } } The above program takes the name of a file as the parameter. This function will remove the file specified from disk. Give the dir command at the command prompt and you will find that the file has been deleted. Every language will offer you millions of such functions like copy and delete. These functions were always available, but C# has gone one step further and made these functions a part of a Class. They are now part of a Namespace. Hence it becomes easier to categorize functions. It is but a question of detail whether you should or should not categorize them.