Grouping related classes in a logical manner is always a good thing. Preventing naming clashes or ambiguity is another good reason. A third reason would be for specialized classes in the area of inheritance and class polymorphism As an example:
If you have classes in two different namespaces that one of the class relies on for input or a property of some kind then you might see something like the following:
Code:
namespace Test.CSharpExample.ImplementsA
{
public class Hello
{
private string m_Message;
public string Message
{
get
{
return m_Message;
}
set
{
m_Message = value;
}
}
}
}
Code:
namespace Test.CSharpExample.InheritsB
{
abstract class Hello // Abstract class
{
protected string m_Message = "";
public abstract void AbstractMethod(); // Abstract method
public abstract string Message {get;}{set;}
}
}
and if you would like to derive the properties and methods of the InheritsB Hello class or instance the ImplementsA Hello class:
Code:
using System;
using System.Collections.Generic;
using System.Text;
using Test.CSharpExample.ImplementsA;
using Test.CSharpExample.InheritsB;
namespace Test.CSharpExample.DerivedOrImplementedClasses
{
class DerivedClass : Test.CSharpExample.InheritsB.Hello
{
public override void AbstractMethod()
{
m_Message = "Hello, World";
}
public override string Message // overriding property
{
get
{
return m_Message;
}
set
{
m_Message = value;
}
}
static void Main()
{
DerivedClass o = new DerivedClass();
Test.CSharpExample.ImplementsA.Hello o2 = new Test.CSharpExample.ImplementsA.Hello();
o.AbstractMethod();
o2.Message.ToString();
Console.WriteLine("{0}", o.Message);
Console.WriteLine(o2.Message.ToString());
}
}
}
As you can see you can do both within the same operator class. With namespaces you can logically organize, provide a way to distinguish between differing subtypes of a class to avoid inconsitency or ambiguity, provide yourself with a shortcut to writing cleaner more readable code and you can provide for both inheritance and implementation within the same namespace
