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<T>(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:
<baz>
<test>Testing</test>
</baz>
Will be wrapped in an evelope like this:
<evelope>
<messageType>urn:My.Namespace:Foo+Bar+Baz</messageType>
<message>
<test>Testing</test>
</message>
</evelope>