Friday, 17 August 2018

C#: Namespaces

Namespaces are used to organize your application logic. If you are aware of java, name spaces are equivalent to packages in java.

How to define namespace?
‘namespace’ keyword is used to define name space.

Syntax
namespace nameSpaceName{
         //Block of statements
}

Example
namespace NameSpace1
{
    class Arithmetic
    {
        public static int sum(int a, int b)
        {
            return a+b;
        }
    }
}

Above snippet defines a namespace named ‘NameSpace1’. ‘Arithmetic’ class is defined inside the name space ‘NameSpace1’.

How to access the name space?
‘using’ keyword is used to import a namespace into your application.

Syntax
using namespace;

Example
using System;
Console.WriteLine("Hello, World!");

You can also access the name space, by using the fully qualified name like below.
System.Console.WriteLine("Hello, World!");

Following is the complete working application.

Program.cs
using System;

namespace NameSpace1
{
    class Arithmetic
    {
        public static int sum(int a, int b)
        {
            return a+b;
        }
    }
}


class Program
{
    static void Main(string[] args)
    {
        int result1 = NameSpace1.Arithmetic.sum(10, 20);

        Console.WriteLine("Sum of 10 and 20 is {0}", result1);
    }

}


Output
Sum of 10 and 20 is 30




Previous                                                 Next                                                 Home

No comments:

Post a Comment