SlideShare a Scribd company logo
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.

More Related Content

Viewers also liked

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 Part2
Mohamed Krar
 
Proyecto On Site
Proyecto On SiteProyecto On Site
Proyecto On Site
guest9796c0
 
Amor
AmorAmor
Amor
auricola
 
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
Raúl Pleguezuelo
 
B L O G’ S
B L O G’ SB L O G’ S
B L O G’ S
grupodesabado
 
Circo
CircoCirco
Desem Ki
Desem KiDesem Ki
Desem Ki
tuncel99
 
Árvores de minha infância
Árvores de minha infânciaÁrvores de minha infância
Árvores de minha infância
Vera 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
 
Csharp_Contents
Csharp_ContentsCsharp_Contents
Csharp_Contents
Mohamed Krar
 
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 Criadas
viola
 
01 Pohledy Evropa
01 Pohledy Evropa01 Pohledy Evropa
01 Pohledy Evropa
jedlickak01
 
01 Pohledy Nejlepší Pohledy Hor
01 Pohledy Nejlepší Pohledy Hor01 Pohledy Nejlepší Pohledy Hor
01 Pohledy Nejlepší Pohledy Horjedlickak01
 
Onassis
OnassisOnassis
Onassis
macuario
 

Viewers also liked (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
 

Similar to Csharp_Chap02

Csharp_Chap03
Csharp_Chap03Csharp_Chap03
Csharp_Chap03
Mohamed Krar
 
Csharp_Chap04
Csharp_Chap04Csharp_Chap04
Csharp_Chap04
Mohamed Krar
 
Csharp_Chap06
Csharp_Chap06Csharp_Chap06
Csharp_Chap06
Mohamed Krar
 
Csharp_Chap08
Csharp_Chap08Csharp_Chap08
Csharp_Chap08
Mohamed Krar
 
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.
Andrey Karpov
 
Java concurrency questions and answers
Java concurrency questions and answers Java concurrency questions and answers
Java concurrency questions and answers
CodeOps Technologies LLP
 
06 abstract-classes
06 abstract-classes06 abstract-classes
06 abstract-classes
Abhishek Khune
 
LEARN C#
LEARN C#LEARN C#
LEARN C#
adroitinfogen
 
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
HUJAK - Hrvatska udruga Java korisnika / Croatian Java User Association
 
Inheritance
InheritanceInheritance
Inheritance
Daman Toor
 
Synapseindia dot net development
Synapseindia dot net developmentSynapseindia dot net development
Synapseindia dot net development
Synapseindiappsdevelopment
 
06 abstract-classes
06 abstract-classes06 abstract-classes
06 abstract-classes
Anup Burange
 
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)
Akhil Mittal
 
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.
PVS-Studio
 
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
AVINASH KUMAR
 
Advance java kvr -satya
Advance java  kvr -satyaAdvance java  kvr -satya
Advance java kvr -satya
Satya Johnny
 
Adv kvr -satya
Adv  kvr -satyaAdv  kvr -satya
Adv kvr -satya
Jyothsna Sree
 
Unit2 java
Unit2 javaUnit2 java
Unit2 java
mrecedu
 
Chapter 9 Abstract Class
Chapter 9 Abstract ClassChapter 9 Abstract Class
Chapter 9 Abstract Class
OUM SAOKOSAL
 
E5
E5E5
E5
lksoo
 

Similar to Csharp_Chap02 (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
 

More from Mohamed Krar

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

More from 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
 

Recently uploaded

AppSec PNW: Android and iOS Application Security with MobSF
AppSec PNW: Android and iOS Application Security with MobSFAppSec PNW: Android and iOS Application Security with MobSF
AppSec PNW: Android and iOS Application Security with MobSF
Ajin Abraham
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
DanBrown980551
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
Zilliz
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
akankshawande
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Safe Software
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
ssuserfac0301
 
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge GraphGraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
Neo4j
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
Edge AI and Vision Alliance
 
Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
panagenda
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
Jason Packer
 
"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor Ivaniuk
"Frontline Battles with DDoS: Best practices and Lessons Learned",  Igor Ivaniuk"Frontline Battles with DDoS: Best practices and Lessons Learned",  Igor Ivaniuk
"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor Ivaniuk
Fwdays
 
"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota
Fwdays
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
Zilliz
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Tosin Akinosho
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
Hiroshi SHIBATA
 
Essentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation ParametersEssentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation Parameters
Safe Software
 
Y-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PPY-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PP
c5vrf27qcz
 
Apps Break Data
Apps Break DataApps Break Data
Apps Break Data
Ivo Velitchkov
 
“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...
“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...
“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...
Edge AI and Vision Alliance
 

Recently uploaded (20)

AppSec PNW: Android and iOS Application Security with MobSF
AppSec PNW: Android and iOS Application Security with MobSFAppSec PNW: Android and iOS Application Security with MobSF
AppSec PNW: Android and iOS Application Security with MobSF
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
 
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge GraphGraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
 
Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
 
"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor Ivaniuk
"Frontline Battles with DDoS: Best practices and Lessons Learned",  Igor Ivaniuk"Frontline Battles with DDoS: Best practices and Lessons Learned",  Igor Ivaniuk
"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor Ivaniuk
 
"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota"Choosing proper type of scaling", Olena Syrota
"Choosing proper type of scaling", Olena Syrota
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
 
Essentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation ParametersEssentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation Parameters
 
Y-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PPY-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PP
 
Apps Break Data
Apps Break DataApps Break Data
Apps Break Data
 
“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...
“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...
“How Axelera AI Uses Digital Compute-in-memory to Deliver Fast and Energy-eff...
 

Csharp_Chap02

  • 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.