Skip to content

Instantly share code, notes, and snippets.

@roboryantron
Created March 25, 2021 14:32
Show Gist options
  • Select an option

  • Save roboryantron/af604cadf58156235e8cf7a948a331d4 to your computer and use it in GitHub Desktop.

Select an option

Save roboryantron/af604cadf58156235e8cf7a948a331d4 to your computer and use it in GitHub Desktop.
public override string ToString()
{
const BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.IgnoreCase | BindingFlags.Instance;
string result = $"{GetType().Name}:";
FieldInfo[] fields = GetType().GetFields(flags);
for (int i = 0; i < fields.Length; i++)
{
result += $"\n {fields[i].Name} = {fields[i].GetValue(this)}";
}
return result;
}
@roboryantron
Copy link
Author

Depending on how much this is getting used, you could use a static string builder rather than the constant concatenation. You could also cache the field info list to reduce reflection

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment