Saturday, 18 August 2018

C#: Resolving name space conflicts

In any application, it is very common to use multiple name spaces. It may happen that, more than one name space may have same class name. if you try to use the class name defined in more than one imported name spaces, C# compiler shows the conflict.

Program.cs
using System;
using NameSpace1;
using NameSpace2;

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

namespace NameSpace2
{
    class Arithmetic
    {
        static float sum(float a, float b)
        {
            return a + b;
        }
    }
}

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

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

}


As you see Program.cs, I  defined the class 'Arithmetic' in the name spaces NameSpace1 and NameSpace2. When I try to use the method 'Arithmetic.sum(10, 20);', compiler don't know which method it should use (Since Arithmetic class is defined in both the name spaces NameSpace1, NameSpace2).

To resolve this conflict, we should use the fully qualified name like below.

 // To use the Arithmetic class defined in NameSpace1
NameSpace1.Arithmetic.sum(10, 20);    

 // To use the Arithmetic class defined in NameSpace2
NameSpace2.Arithmetic.sum(10, 20);    

Following is the updated application.

Program.cs
using System;
using NameSpace1;
using NameSpace2;

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

namespace NameSpace2
{
    class Arithmetic
    {
        static float sum(float a, float 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