Thursday, February 10, 2011

Namespaces vs Packages

A C# namespace is a way to group a collection of classes and is used in a manner similar to Java's package construct. Users of C++ will notice the similarities between the C# namespace syntax and that in C++. In Java, the package names dictate the directory structure of source files in an application whereas in C# namespaces do not dictate the physical layout of source files in directories only their logical structure. Examples below:
C# Code

namespace com.carnage4life{

public class MyClass {

int x;

void doStuff(){}

}

}

Java Code
package com.carnage4life;

public class MyClass {

int x;

void doStuff(){}

}
C# namespace syntax also allows one to nest namespaces in the following way
C# Code
using System;

namespace Company{

public class MyClass { /* Company.MyClass */

int x;

void doStuff(){}

}

namespace Carnage4life{

public class MyOtherClass { /* Company.Carnage4life.MyOtherClass */

int y;

void doOtherStuff(){}

public static void Main(string[] args){

Console.WriteLine("Hey, I can nest namespaces");
}

}// class MyOtherClass
}// namespace Carnage4life
}// namespace Company

No comments:

Post a Comment