https://github.com/winseros/tostringdotnet
Will help you to avoid handwriting ToString methods for your .NET projects
https://github.com/winseros/tostringdotnet
csharp tostring
Last synced: 11 months ago
JSON representation
Will help you to avoid handwriting ToString methods for your .NET projects
- Host: GitHub
- URL: https://github.com/winseros/tostringdotnet
- Owner: winseros
- License: mit
- Created: 2020-06-01T16:18:58.000Z (about 6 years ago)
- Default Branch: master
- Last Pushed: 2022-06-07T11:09:52.000Z (about 4 years ago)
- Last Synced: 2025-08-15T07:20:43.787Z (11 months ago)
- Topics: csharp, tostring
- Language: C#
- Size: 31.3 KB
- Stars: 3
- Watchers: 1
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# ToStringDotNet
The library purpose is to save you from handrwiting `ToString()` method implementations for your objects.
Instead of:
```csharp
class MyClass
{
public string MyProperty { get; set; }
public void ToString()
{
var sb = new StringBuilder();
sb.Append("{\"MyProperty\":\"");
sb.Append(this.MyProperty);
sb.Append("\"}");
return sb.ToString();
}
}
```
You can write:
```csharp
class MyClass
{
[ToString]
public string MyProperty { get; set; }
public void ToString()
{
return ToStringFormatter.Format(this);
}
}
```
## How to
### Print an object
```csharp
class MyClass
{
[ToString]
public string MyProperty1 { get; set; }
[ToString]
public int MyProperty2 { get; set; }
}
...
var obj = new MyObject{MyProperty1 = "p1", MyProperty2 = 1};
var str = ToStringFormatter.Format(obj);
Console.WriteLine(str);
//{"MyProperty1":"p1","MyProperty2":1}
```
### Reorder properties
```csharp
class MyClass
{
[ToString(1)] //lower priority - goes last
public string MyProperty1 { get; set; }
[ToString(2)] //higher priority - goes first
public int MyProperty2 { get; set; }
}
...
var obj = new MyObject{MyProperty1 = "p1", MyProperty2 = 1};
var str = ToStringFormatter.Format(obj);
Console.WriteLine(str);
//{"MyProperty2":1,"MyProperty1":"p2"}
```
### Exclude inherited properties
```csharp
class MyParentClass
{
[ToString]
public string MyProperty1 { get; set; }
}
[ToStringInheritance(ToStringInheritance.NotInherit)]
class MyChildClass: MyParentClass
{
[ToString]
public string MyProperty2 { get; set; }
}
...
var obj = new MyChildClass{MyProperty1 = "p1", MyProperty2 = "p2"};
var str = ToStringFormatter.Format(obj);
Console.WriteLine(str);
//{"MyProperty2":"p2"}
```
### More examples
For more examples see the [ToStringDotNet.Test](./ToStringDotNet.Test) project.