How can I retrieve the namespace to a string C#

Elliot Ames picture Elliot Ames · Aug 28, 2013 · Viewed 68.8k times · Source

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.

Answer

Joe Ratzer picture Joe Ratzer · Aug 28, 2013

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;
}