Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This one is not fully baked as we just came up with it this morning. It will generate a full class definition for a Type. Useful for situations where you have a a large class and want to create a subset or full definition but don't have access to it. For example, to store the object in a database etc.</p> <pre><code>public static class TypeExtensions { public static string GenerateClassDefinition(this Type type) { var properties = type.GetFields(); var sb = new StringBuilder(); var classtext = @"private class $name { $props}"; foreach (var p in GetTypeInfo(type)) { sb.AppendFormat(" public {0} {1} ", p.Item2, p.Item1).AppendLine(" { get; set; }"); } return classtext.Replace("$name", type.Name).Replace("$props", sb.ToString()); } #region Private Methods private static List&lt;Tuple&lt;string, string&gt;&gt; GetTypeInfo(Type type) { var ret = new List&lt;Tuple&lt;string, string&gt;&gt;(); var fields = type.GetFields(); var props = type.GetProperties(); foreach(var p in props) ret.Add(new Tuple&lt;string, string&gt;(p.Name, TranslateType(p.PropertyType))); foreach(var f in fields) ret.Add(new Tuple&lt;string, string&gt;(f.Name, TranslateType(f.FieldType))); return ret; } private static string TranslateType(Type input) { string ret; if (Nullable.GetUnderlyingType(input) != null) { ret = string.Format("{0}?", TranslateType(Nullable.GetUnderlyingType(input))); } else { switch (input.Name) { case "Int32": ret = "int"; break; case "Int64": ret = "long"; break; case "IntPtr": ret = "long"; break; case "Boolean": ret = "bool"; break; case "String": case "Char": case "Decimal": ret = input.Name.ToLower(); break; default: ret = input.Name; break; } } return ret; } #endregion } </code></pre> <p>Example usage:</p> <pre><code>Process.GetProcesses().First().GetType().GenerateClassDefinition(); </code></pre> <p>Becomes even more handy if using linqpad:</p> <pre><code>Process.GetProcesses().First().GetType().GenerateClassDefinition().Dump(); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload