Auto-generates ToString()
based on your class's fields and/or properties.
This is an add-in for PostSharp. It modifies your assembly during compilation by using IL weaving.
Your code:
[ToString]
class TestClass
{
public int Foo { get; set; }
public double bar;
[IgnoreDuringToString]
public string Baz { get; set; }
}
What gets compiled:
class TestClass
{
public int Foo { get; set; }
public double bar;
public string Baz { get; set; }
public override string ToString()
{
return $"TestClass; Foo:{Foo},bar:{bar}";
}
}
- Install the NuGet package:
PM> Install-Package PostSharp.Community.ToString
- Get a free PostSharp Community license at https://www.postsharp.net/get/free
- When you compile for the first time, you'll be asked to enter the license key.
Add [ToString]
to the classes where you want to generate ToString, or use multicasting.
You can also use [IgnoreDuringToString]
to exclude some fields or properties from ToString.
You can also set some formatting options in the properties of the ToString
attribute. You can also set these formatting options
globally by adding the assembly-wide attribute [assembly:ToStringGlobalOptions]
.
Possible options are:
- PropertiesSeparator
- PropertyNameToValueSeparator
- WriteTypeName
- WrapWithBraces
- IncludePrivate (includes also private members)
- PropertyNamingConvention (CamelCase option)
ToString will include all non-private fields and properties from the class including accessible fields and properties from any base classes.
For arrays and collections, ToString will print the first four elements of the collection, separated by PropertiesSeparator (for example, [1,2,3,4,...]
for an array of 5 or more integers).
If you want to exclude some fields or properties from ToString everywhere, for example, exclude everything that's protected, you can multicast the [IgnoreDuringToString]
attribute like this:
[assembly: IgnoreDuringToString(AttributeTargetMemberAttributes = MulticastAttributes.Protected)
Published under the MIT license.
- Copyright © PostSharp Technologies, Simon Cropp, and contributors
- Icon by Smashicons from www.flaticon.com