Tanoda
TypeNameExtensions.cs
Go to the documentation of this file.
1using System;
2using System.Collections.Generic;
3using System.Linq;
4
6{
7 public static class TypeNameExtensions
8 {
9 public static string GetSourceCodeRepresentation(this Type type)
10 {
11 try
12 {
13 return GetSourceCodeRepresentationInt(type, new List<Type>());
14 }
15 catch
16 {
17 return type.FullName;
18 }
19 }
20
21 private static string GetSourceCodeRepresentationInt(Type type, List<Type> travesed)
22 {
23 // Potential infinite recursion
24 if (travesed.Count > 20) throw new ArgumentException();
25
26 travesed.Add(type);
27
28 var prefixName = string.Empty;
29 if (type.DeclaringType != null)
30 {
31 if (!travesed.Contains(type.DeclaringType))
32 prefixName = GetSourceCodeRepresentationInt(type.DeclaringType, travesed) + ".";
33 }
34 else if (!string.IsNullOrEmpty(type.Namespace))
35 prefixName = type.Namespace + ".";
36
37 if (type.IsGenericType)
38 {
39 // Fill the list with nulls to preserve the depth
40 var genargNames = type.GetGenericArguments().Select(type1 => GetSourceCodeRepresentationInt(type1, new List<Type>(Enumerable.Repeat<Type>(null, travesed.Count))));
41 var idx = type.Name.IndexOf('`');
42 var typename = idx > 0 ? type.Name.Substring(0, idx) : type.Name;
43 return string.Format("{0}{1}<{2}>", prefixName, typename, string.Join(", ", genargNames.ToArray()));
44 }
45
46 if (type.IsArray)
47 {
48 return string.Format("{0}[{1}]", GetSourceCodeRepresentation(type.GetElementType()),
49 new string(Enumerable.Repeat(',', type.GetArrayRank() - 1).ToArray()));
50 }
51
52 return string.Format("{0}{1}", prefixName, type.Name);
53 }
54 }
55}