I'm a Java Developer, used to the 'generate toString()' option in Eclipse which offers a complete toString, printing values of all instance variables. I'm just looking for the comparable shortcut in Visual Studio.
I've seen how you can begin typing the method, "public override " and autocomplete will stub a ToString() but it will not fill it in with all the class properties.
public override string ToString()
{
return base.ToString();
}
I'd like the generated method to include all properties of the class.
You could do this by using reflection. But that can cause performance issues if you have to call that method very often in a short time. And it is not that trivial to code with reflection.
The Visual Studio addon Resharper has this feature:
alt + Insert -> Generate -> Formatting members -> select all -> finish
Probably the easiest solution, when you only need public properties. It does not work with public fields.
For .Net-Framework with the NewtonSoft.Json nuget
using Newtonsoft.Json;
public override string ToString()
{
return JsonConvert.SerializeObject(this);
}
for .Net 5 and newer with System.Text.Json
using System.Text.Json;
public override string ToString()
{
return JsonSerializer.Serialize(this);
}