HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Get nested type name without namespace

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
withouttypenestedgetnamenamespace

Problem

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(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:


Testing



Will be wrapped in an evelope like this:


urn:My.Namespace:Foo+Bar+Baz

Testing


Solution

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.

Code Snippets

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

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

Context

StackExchange Code Review Q#47804, answer score: 5

Revisions (0)

No revisions yet.