C# - Create a User-defined Namespace

In this example, we are going to learn how to create a user-defined namespace using C# program?
Submitted by Nidhi, on September 11, 2020 [Last updated : March 22, 2023]

A namespace is used to logically group similar types of classes, structures, interfaces, delegates, etc. Here, we will create a user-defined namespace using the namespace keyword.

C# program to create a user-defined namespace

The source code to create a user-defined namespace is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.

//C# - Create a User-defined Namespace

using System;

namespace Test.Namespace
{
    class Sample
    {
        public static void Swap(ref int X, ref int Y)
        {
            int Z = 0;

            Z = X;
            X = Y;
            Y = Z;
        }
    }
}
class Program
{
    static void Main()
    {
        int X = 10;
        int Y = 20;

        Console.WriteLine("Before swapping : X " + X + ", Y " + Y);
        Test.Namespace.Sample.Swap(ref X, ref Y);

        Console.WriteLine("After swapping  : X " + X + ", Y " + Y);
        Console.WriteLine();
    }
}

Output

Before swapping : X 10, Y 20
After swapping  : X 20, Y 10

Press any key to continue . . .

Explanation

In the above program, we created a user-defined namespace "Test.Namespace" that contains a Sample class. The Sample class contains a Swap() method. The Swap() method will interchange the values of parameters with each other.

Here we also created a Program class that contains the Main() method. In the Main() method, we created two local variables X and Y. Then swap the values using the Swap() method and print the swapped value on the console screen.

C# Basic Programs »


Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.