How can I retrieve the namespace to a string C#

I am writing a program which needs the namespace of the program but I cant seem to figure out how to retrieve it. I would like the end result to be in a string.

I was able to find an MSDN page about this topic but it proved to be unhelpful to myself. http://msdn.microsoft.com/en-us/library/system.type.namespace.aspx

Any help would be appreciated. The program is written in C#.

EDIT: Sorry guys, this is not a console application.


Solution 1:

This should work:

var myType = typeof(MyClass);
var n = myType.Namespace;

Write out to the console:

Type myType = typeof(MyClass);
Console.WriteLine("Namespace: {0}.", myType.Namespace);

Setting a WinForm label:

Type myType = typeof(MyClass);
namespaceLabel.Text = myType.Namespace;

Or create a method in the relevant class and use anywhere:

public string GetThisNamespace()
{
   return GetType().Namespace;
}

Solution 2:

To add to all the answers.

Since C# 6.0 there is the nameof keyword.

string name = nameof(MyNamespace);

This has several advantages:

  1. The name is resolved at compile-time
  2. The name will change when refactoring the namespace
  3. It is syntax checked, so the name must exist
  4. cleaner code

Note: This doesn't give the full namespace though. In this case, name will be equal to Bar:

namespace Foo.Bar
{
   string name = nameof(Foo.Bar);
}