TooString 0.8.2-preview

This is a prerelease version of TooString.
There is a newer prerelease version of this package available.
See the version list below for details.
dotnet add package TooString --version 0.8.2-preview
                    
NuGet\Install-Package TooString -Version 0.8.2-preview
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="TooString" Version="0.8.2-preview" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="TooString" Version="0.8.2-preview" />
                    
Directory.Packages.props
<PackageReference Include="TooString" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add TooString --version 0.8.2-preview
                    
#r "nuget: TooString, 0.8.2-preview"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package TooString@0.8.2-preview
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=TooString&version=0.8.2-preview&prerelease
                    
Install as a Cake Addin
#tool nuget:?package=TooString&version=0.8.2-preview&prerelease
                    
Install as a Cake Tool

TooString is a Stringifier that goes places serializers don't.

TooString can

  • make a best effort to stringify objects that JsonSerializer won't, including System.Reflection classes and System.Type; or for which JsonSerializer returns empty output, such as ValueTuples.
  • Output as Json or C# object notation, or 'debug view' style, or [CallerArgumentExpression]

TooString offers 5 extension method groups on Object:

value.ToCSharpString()
value.ToJson();
value.ToSTJson()
value.TooString();
value.ToArgumentExpression();

TooString is not a serializer.

  • A serializer should be fail-fast, but TooString is best-effort.
  • A Serializer should throw if it cannot deterministically serialize the input, but TooString will attempt to return a partial or alternative representation of the input if the input cannot be reliably serialized.
  • TooString offers both MaxDepth and MaxEnumerationLength options for abbreviated output.

Default behaviour

  • ToCSharpString() returns C# code creating anonymous objects, with Type names in comments.
  • ToJson() returns JSON.
  • ToSTJson() is a convenience method for System.Text.Json.JsonSerializer.Serialize(...).
  • TooString() defaults to CSharp style; pass StringifyAs to choose an alternative output.
  • ToArgumentExpression() returns the literal code expression.

Object output defaults to MaxDepth = 3, MaxEnumerationLength = 9, except for ToSTJson() which behaves identically to calling System.Text.Json.JsonSerializer.Serialize directly.

What's the different between ToJson() and ToSTJson()?

  • System.Text.Json throws given unserializable types or values anywhere in the obkjecor if there are errors during serialization. ToJson() will catch errors and return what it's got.
  • System.Text.Json will return "{}" by default for any ValueTuple. ToJson() will return the tuple items as an array.
  • ToJson() can abbreviate output with both maxDepth and maxEnumerableLength options, System.Text.Json has no maxEnumerableLength option.
  • System.Text.Json will return property values for classes in System.Numerics, ToJson() will represent multi-dimensional numbers as arrays.
  • ToJson() has a whichProperties (default is BindingFlags.Instance | BindingFlags.Public) property to choose which members to stringify. STJ has an includeFields and IgnoreReadOnly... properties, and then offers TypeInfoResolvers.

Example:

var value = new { A = "boo", B = new Complex(3,4) };

value.ToCSharpString()  // Output is { A = "boo", B = <3; 4> } depending on .Net version.
value.ToJson();         // Output is reflection-based JSON: {"A":"boo","B":[3,4]}
value.ToSTJson();       // Output is System.Text.Json: {"A":"boo","B":{"Real":3,...}}

( Math.Sqrt(4 * Math.PI / 3)  ).ToArgumentExpression() 
// Output is the literal code: "Math.Sqrt(4 * Math.PI / 3)"

var tuple = (one: 1, two: "2", three: new Complex(3,4));

System.Text.Json.JsonSerializer.Serialize(tuple) // Output is "{}" because there  
                                                 // are no public properties on a tuple

tuple.ToJson()
// Output stringifies the tuple and the Complex number as arrays
// [1,"2",[3,4]] 

tuple.ToCSharpString()
// Output is created by reflection and 
// on Net6.0 : (1, "2", (3,4))  
// on Net8.0+: (1, "2", <3;4>)

var type = value.GetType();
System.Text.Json.JsonSerializer.Serialize(type) // Throws NotSupportedException
type.ToJson() // Outputs the type object, truncated to default MaxDepth = 3, MaxEnumerationLength = 9

Options

Options, and their default values, are:

 bool writeIndented = true,
 BindingFlags whichProperties = BindingFlags.Instance | BindingFlags.Public,
 int maxDepth = 3,
 int maxEnumerableLength = 9,
 string dateTimeFormat = "O",
 string dateOnlyFormat = "O",
 string timeOnlyFormat = "HH:mm:ss",
 string timeSpanFormat = "c"

maxEnumerableLength=0 means show zero elements. To show unlimited elements, use int.MaxValue

Options for ToSTJson() are the framework provided JsonSerializerOptions:

bool writeIndented = false,
 JsonNamingPolicy? propertyNamingPolicy = null,
 JsonIgnoreCondition defaultIgnoreCondition = JsonIgnoreCondition.Never,
 JsonNumberHandling numberHandling = JsonNumberHandling.Strict,
 ReferenceHandler? referenceHandler = null,
 bool propertyNameCaseInsensitive = false,
 bool includeFields = false,
 int maxDepth = 0,
 bool allowTrailingCommas = false,
 JsonCommentHandling readCommentHandling = JsonCommentHandling.Disallow,
 System.Text.Encodings.Web.JavaScriptEncoder? encoder = null

More Examples

// Reflection-based JSON
value.ToJson()
value.ToJson(writeIndented: true, maxDepth: 5)

// C# object notation
value.ToCSharpString()
value.ToCSharpString(writeIndented: true, maxDepth: 5)

// System.Text.Json
value.ToSTJson()
value.ToSTJson(writeIndented: true, propertyNamingPolicy: JsonNamingPolicy.CamelCase)

// TooString with style selection
value.TooString()
value.TooString(StringifyAs.JsonStringifier)
value.TooString(maxDepth: 4, maxEnumerableLength: 9, style: StringifyAs.CSharp)
value.TooString(TooStringOptions.ForJson with { MaxEnumerationLength = 9 })

Gotchas

Example: Json-serializing value tuples is something of a surprise because (unlike anonymous objects or records or structs) they have no public properties and their public fields are not named as per your code. Takeaway: don't choose value tuples for public apis that must be jsonned.

System.Text.Json.JsonSerializer.Serialize(  (one:1, two:"2")  )
// Output is "{}" because there are no public fields

(one:1, two:"2").ToJson()
// Output is [1,"2"]. 
// The value tuple is detected as an ITuple, and we use reflection instead

ChangeLog

<pre> ChangeLog

0.8.x Simplify to: ToCSharpString(), ToJson(), ToSTJson(), TooString(), ToArgumentExpression(). Offer individual parameters in preference to a TooStringOptions object. 0.7.0 Easier to build new TooStringOptions(){...}. Sanitize overloads. 0.6.0 TooString() defaults to CSharp. 0.5.0 ReflectionOptions.With(...), TooStringOptions.With(...). Fixes. 0.4.0 ReflectionOptions.MaxLength default = 9 ReflectionOptions.ForJson and ReflectionOptions.ForDebugView instead of Default. More overloads. 0.3.0 ReflectionOptions.MaxLength limits display of enumerable elements 0.2.0 Added Net8 (NB Net8 Json and Numerics output is different from Net6) Rename StringifyAs to TooStringHow. Fix SerializationStyle.Reflection output of DateTime, DateOnly, TimeOnly. 0.1.0 Can use DebugView, Json, ToString() or [CallerArgumentExpression] and can output Json or Debug strings. </pre>

Product Compatible and additional computed target framework versions.
.NET net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • net10.0

    • No dependencies.
  • net6.0

    • No dependencies.
  • net8.0

    • No dependencies.

NuGet packages (2)

Showing the top 2 NuGet packages that depend on TooString:

Package Downloads
TestBase

*TestBase* gives you a flying start with - fluent assertions that are easy to extend - sharp error messages - tools to help you test with “heavyweight” dependencies on - AspNetCore.Mvc, AspNet.Mvc or WebApi Contexts - HttpClient - Ado.Net - Streams & Logging - Mix & match with your favourite test runners & assertions. ``` UnitUnderTest.Method() .ShouldNotBeNull() .ShouldEqualByValueExceptFor(new {Id=1, Descr=expected}, ignoreList ) .Payload .ShouldMatchIgnoringCase("I expected this") .Should(someOtherPredicate); .Items .ShouldAll(predicate) .ShouldContain(item) .ShouldNotContain(predicate) .Where(predicate) .SingleOrAssertFail() item .ShouldEqualByValue() .ShouldEqualByValueExceptFor(...) .ShouldEqualByValueOnMembers() string .ShouldMatch(pattern) .ShouldNotMatch() .ShouldBeEmpty() .ShouldNotBeEmpty() .ShouldNotBeNullOrEmptyOrWhiteSpace() .ShouldEqualIgnoringCase() .ShouldContain() .ShouldBeContainedIn() .ShouldStartWith() .ShouldEndWith() ... numeric .ShouldBeBetween() .ShouldEqualWithTolerance()....GreaterThan....LessThan...GreaterOrEqualTo ... ienumerable .ShouldAll() .ShouldContain() .ShouldNotContain() .ShouldBeEmpty() .ShouldNotBeEmpty() ... stream .ShouldHaveSameStreamContentAs() .ShouldContain() value .ShouldBe() .ShouldNotBe() .ShouldBeOfType() .ShouldBeAssignableTo() ... ``` Testable Logging is in packages Extensions.Logging.ListOfString and Serilog.Sinks.ListOfString ``` // Extensions.Logging.ListOfString var log = new List<String>(); ILogger mslogger= new LoggerFactory().AddStringListLogger(log).CreateLogger("Test2"); // Serilog.Sinks.ListOfString Serilog.Logger slogger= new LoggerConfiguration().WriteTo.StringList(log).CreateLogger(); ```

TestBase.Differ

TestBase.Differ provides deep comparison of objects, collections and strings, with human readable output options. ```csharp var result = Differ.Diff(expected, actual, options); if (!result) // Implicit bool conversion { Console.WriteLine(result.ToString()); } ```

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.8.8-preview 0 4/26/2026
0.8.7-preview 22 4/26/2026
0.8.6-preview 24 4/26/2026
0.8.4-preview 38 4/25/2026
0.8.3-preview 99 4/21/2026
0.8.2-preview 127 4/20/2026
0.8.1-preview 168 4/19/2026
0.7.0-preview 215 4/1/2026
0.6.0 141 3/29/2026
0.5.1-preview 282 3/26/2026
0.5.0-preview 226 6/30/2025
0.4.0-preview 4,666 6/24/2025
0.3.0-preview 264 6/24/2025
0.2.0-preview 230 6/20/2025
0.1.0 2,545 7/11/2024

ChangeLog
           ---------
           0.8.x  Simplify to: ToCSharpString(), ToJson(), ToSTJson(), TooString(), ToArgumentExpression().
                  Offer individual parameters in preference to a TooStringOptions object.
           0.7.0  Easier to build new TooStringOptions(){...}. Sanitize overloads.
           0.6.0  TooString() defaults to CSharp.
                  Add TooStringOptions.WriteIndented property.
                  Delete redundant styles.
           0.5.1  ReflectionOptions.Json and JsonOptions.WriteIndented output matchs STJ indentation. | Added net10.0
           0.5.0  ReflectionOptions.MaxEnumerationLength renamed from MaxLength | Options.With(...) methods for easy configuration
           0.4.0  ReflectionOptions.MaxLength default = 9 | ReflectionOptions.ForJson and ReflectionOptions.ForDebugView instead of Default | More overloads.
           0.3.0  ReflectionOptions.MaxLength limits display of enumerable elements
           0.2.0  Added Net8 (NB Net8 Json and Numerics output is different from Net6)
                  Rename TooStringStyle to TooStringHow.
                  Fix SerializationStyle.Reflection output of DateTime, DateOnly, TimeOnly.
           0.1.0  Can use DebugView, Json, ToString() or [CallerArgumentExpression] and can output Json or Debug strings.