Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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


This post first appeared on Java Tutorial : Blog To Learn Java Programming, please read the originial post: here

Share the post

C#: Resolving name space conflicts

×

Subscribe to Java Tutorial : Blog To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×