Get nested type name without namespace Suppose I have a nested class structure like this:

namespace My.Namespace {
    public class Foo {
        public class Bar {
            public class Baz {
                public string Test { get; set; }
            }
        }
    }
}


I need to get the nested type name of Baz without the namespace, i.e. Foo+Bar+Baz in a generic method. Unfortunately, .Name will just return Baz and .FullName will give me the namespace as well. Right now I'm using this:

protected T LoadSample&lt;T&gt;(string fileName) 
{
    var t = typeof(T);
    var nestedTypeName = t.Namespace == null
        ? t.FullName                                 // T is declared outside of a namespace
        : t.FullName.Substring(t.Namespace.Length + 1);
    ...
}


But this just looks ugly. Is there a more standard method for getting just Foo+Bar+Baz in this situation?

To clarify what's going on inside this method, this is part of a unit test for an XML serialization class. LoadSample will load an XML file, wrap it in a little more XML to create an 'envelope', attempt to parse it, and return the result if it succeeds. The problem is that the 'envelope' that the XML serialization class expects the XML to specify the type name in a particular format. For example:

&lt;baz&gt;
    &lt;test&gt;Testing&lt;/test&gt;
&lt;/baz&gt;


Will be wrapped in an evelope like this:

&lt;evelope&gt;
    &lt;messageType&gt;urn:My.Namespace:Foo+Bar+Baz&lt;/messageType&gt;
    &lt;message&gt;
        &lt;test&gt;Testing&lt;/test&gt;
    &lt;/message&gt;
&lt;/evelope&gt;
Well, one brute force way of doing it is to recurse over the type's DeclaringType property:

public static string TypeName (Type type)
{
   if(type.DeclaringType == null)
      return type.Name;

   return TypeName(type.DeclaringType) + "." + type.Name;
}


Running the following program:

static void Main(string[] args)
{
   var type = typeof(My.Namespace.Foo.Bar.Baz);
   var name = TypeName(type);
}


returns the name Foo.Bar.Baz as you would expect.