Search code examples
c#visual-studiotostring

How do I generate a ToString() in Visual Studio that includes all properties?


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.


Solution

  • Option 1: Reflection

    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.

    Option 2: Resharper

    The Visual Studio addon Resharper has this feature:
    alt + Insert -> Generate -> Formatting members -> select all -> finish

    Option 3: Fody/ToString nuget package

    Probably the easiest solution, when you only need public properties. It does not work with public fields.

    Option 4: serialize to JSON

    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);
    }