How can I retrieve the namespace to a string C#

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

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

Put this to your assembly:

public static string GetCurrentNamespace()
{
    return System.Reflection.Assembly.GetExecutingAssembly().EntryPoint.DeclaringType.Namespace;
}

Or if you want this method to be in a library used by your program, write it like this:

[System.Runtime.CompilerServices.MethodImpl(MethodImplOptions.NoInlining)]
public static string GetCurrentNamespace()
{
    return System.Reflection.Assembly.GetCallingAssembly().EntryPoint.DeclaringType.Namespace;
}