Skip to content

Instantly share code, notes, and snippets.

@mikegoatly
Created August 17, 2020 13:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikegoatly/216762e1bb7659f46a3dd2d8952b0c1d to your computer and use it in GitHub Desktop.
Save mikegoatly/216762e1bb7659f46a3dd2d8952b0c1d to your computer and use it in GitHub Desktop.
Reverse engineering read/write properties of a type
void Main()
{
Console.WriteLine(GetDefinition<Test>());
/* Prints:
public class Test
{
public System.Int32 Number { get; set; }
public System.String Name { get; set; }
}
*/
}
public static string GetDefinition<T>()
{
var builder = new StringBuilder();
var type = typeof(T);
builder.Append("public class ")
.AppendLine(type.Name)
.AppendLine("{");
var readWriteProperties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(p => p.CanRead && p.CanWrite);
foreach (var property in readWriteProperties)
{
builder.Append(" public ")
.Append(property.PropertyType.FullName)
.Append(" ")
.Append(property.Name)
.AppendLine(" { get; set; }");
}
builder.AppendLine("}");
return builder.ToString();
}
public class Test
{
public int Number { get; set; }
public string Name { get; set; }
public bool ReadOnly {get;}
private bool Hidden {get;set;}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment