Home
Manage Your Code
Snippet: Formatted Type Name (C#)
Title: Formatted Type Name Language: C#
Description: Get a nicely formatted generic type name i.e ("MyGenericClass<MyTypeParam>"). Useful for logging purposes. Views: 251
Author: Stephen Smith Date Added: 10/6/2011
Copy Code  
1        public static string NameEx(this Type type)
2        {
3            if (!type.IsGenericType) return type.Name;
4
5            var genericArguments = type.GetGenericArguments().Select(t => t.NameEx());
6
7            return string.Format("{0}<{1}>", type.Name.Left('`'), genericArguments.Delimit());
8        }
9
10        public enum Inclusion
11        {
12            Include,
13            Exclude
14        }
15
16        public static string Left(this string s, char character, Inclusion inclusion = Inclusion.Exclude)
17        {
18            var pos = s.IndexOf(character);
19            if (pos < 0) return s;
20            return s.Substring(0, inclusion == Inclusion.Exclude ? pos : pos + 1);
21        }
22
23        public static string Delimit<T>(this IEnumerable<T> @this, string delimiter = ",", string quoteChar = "")
24        {
25            if (@this == null)
26                throw new ArgumentNullException("@this", string.Format("The argument {0} cannot be null", "@this"));
27
28            StringBuilder result = new StringBuilder();
29
30            foreach (var item in @this)
31            {
32                result.AppendFormat("{0}{1}{0}{2}", quoteChar, item, delimiter);
33            }
34
35            if (result.Length > 0)
36            {
37                return result.ToString(0, result.Length - (delimiter == null ? 0 : delimiter.Length));
38            }
39            else
40            {
41                return string.Empty;
42            }
43        }
Usage
typeof(MyClass).NameEx();