https://github.com/cmstead/pretty-object
A utility for producing a simple string representation of an object in C#
https://github.com/cmstead/pretty-object
Last synced: about 2 months ago
JSON representation
A utility for producing a simple string representation of an object in C#
- Host: GitHub
- URL: https://github.com/cmstead/pretty-object
- Owner: cmstead
- License: mit
- Created: 2021-02-06T07:45:05.000Z (over 5 years ago)
- Default Branch: main
- Last Pushed: 2021-02-09T00:13:27.000Z (over 5 years ago)
- Last Synced: 2026-04-15T04:08:13.211Z (2 months ago)
- Language: C#
- Size: 9.77 KB
- Stars: 2
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Pretty Object #
Pretty Object is an object pretty-printer for handling Golden Master test output. Pretty Object, out of the box, will print all accessible fields in an object as a new-line delimited output. You can also provide transformations for any field values which either should be ignored, or might need to be modified, such as DateTime comparisons.
## Usage ##
### Just Printing Object Properties ###
Example with Approvals:
```csharp
// Don't forget to add a using statement:
// using PrettyObject;
var testObject = new TestObject();
var objectFieldOutput = PrettyPrinter.PrettyPrint(testObject);
Approvals.Verify(objectFieldOutput);
```
It can also be used as a mixin:
```csharp
// Don't forget to add a using statement:
// using PrettyObject;
var testObject = new TestObject();
Approvals.Verify(testObject.PrettyPrint(testObject));
```
### Modifying Properties Before Printing ###
Using an anonymous object with field name and transformation funcs:
```csharp
var testObject = new TestObject();
var verificationOutput = testObject.PrettyPrint(new
{
StringField = new Func((value)
=> ReverseString(value)),
IntField = new Func((value)
=> (value * 2).ToString())
});
Approvals.Verify(verificationOutput);
```
Using a single func (JavaScript JSON.stringify style transformations):
```csharp
var testObject = new TestObject();
Func transformStringValue = (name, value) =>
{
switch (name)
{
case "StringField":
return ReverseString(value);
default:
return value.ToNullSafeString();
}
};
var objectFieldOutput = testObject.PrettyPrint(transformStringValue);
Approvals.Verify(objectFieldOutput);
```
## Public API ##
- PrettyPrint:
- `public string PrettyPrint(this T objectToPrint)`
- `public string PrettyPrint(this T objectToPrint, Func transformer)`
- `public string PrettyPrint(this T objectToPrint, Func transformer)`
- `public string PrettyPrint(this T objectToPrint, object transformer)`
- All properties for the transformer object must be `Func`
- ToNullSafeString:
- `public string ToNullSafeString(this T value)`
- ToStringOrNull:
- `public string ToStringOrNull(this T value)`
## Thanks and Contributors ##
Big thanks to [@jason-kerney](https://github.com/jason-kerney) for his contributions!