by Emmaneale Mendu
Well, we are done with basic part of classes, by now everyone will know how to use classes. And in this post we will work on a new topic namespaces. Like classes we can have any number of namespaces in our program.A namespace is nothing but a word and with open brace and close brace. The entire class and group of classes are enclosed within the namespace. Example: as shown below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
class abc
{
static void Main()
{
}
}
namespace ns1
{
class ns1_class
{
}
}
namespace ns2
{
class ns2_class
{
}
}
}
namespace Consol
{
class Consol_class
{
}
}
Here you two main namespaces ‘ConsoleApplication2’ and ‘Consol’and inner namespaces with having group of classes.
I will show you the errors and solutions later in this post.
namespace ConsoleApplication2
{
class abc
{
static void Main()
{
ccc();
aaa();
bbb();
Console.ReadKey();
}
public static void ccc()
{
Console.WriteLine("I am in CCC");
}
}
namespace ns1
{
class ns1_class
{
public static void aaa()
{
Console.WriteLine("I am in AAA");
}
}
}
namespace ns2
{
class ns2_class
{
public static void bbb()
{
Console.WriteLine("I am in BBB");
}
}
}
}
Errors:
The name ‘aaa’ does not exist in the current context.
The name ‘bbb’ does not exist in the current context.
In the above example program we are calling methods aaa() and bbb() which are in other namespaces. We need tell to the machine from which namespace the method is called. Like as shown in the below code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
class abc
{
static void Main()
{
ns1.ns1_class.aaa();
ns2.ns2_class.bbb();
ccc();
Console.ReadKey();
}
public static void ccc()
{
Console.WriteLine("I am in CCC");
}
}
namespace ns1
{
class ns1_class
{
public static void aaa()
{
Console.WriteLine("I am in AAA");
}
}
}
namespace ns2
{
class ns2_class
{
public static void bbb()
{
Console.WriteLine("I am in BBB");
}
}
}
}
OutPut
I am in AAA
I am in BBB
I am in CCC
Now we will little different way to call the other namespace methods adding using’s.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ns1;
using ns2;
namespace ConsoleApplication2
{
class abc
{
static void Main()
{
ns1_class.aaa();
ns2_class.bbb();
ccc();
Console.ReadKey();
}
public static void ccc()
{
Console.WriteLine("I am in CCC");
}
}
}
namespace ns1
{
class ns1_class
{
public static void aaa()
{
Console.WriteLine("I am in AAA");
}
}
}
namespace ns2
{
class ns2_class
{
public static void bbb()
{
Console.WriteLine("I am in BBB");
}
}
}
OutPut
I am in AAA
I am in BBB
I am in CCC
No comments:
Post a Comment