14

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.

HoosierDude
  • 181
  • 1
  • 2
  • 10
  • 1
    Have you seen this? https://stackoverflow.com/questions/40506922/visual-studio-2015-extension-to-generate-a-tostring-method-in-a-class – Caius Jard Oct 30 '19 at 10:07
  • 2
    `ToString()` doesn't usually return *all properties of the class*. It has specific uses, you set it up as necessary. But you could: type the properties :), use Reflection, create a code snippet (see the Code Snippet Manager under Tools) that makes it happen, use third-party extensions that provide this functionality. – Jimi Oct 30 '19 at 10:12
  • 1
    What is the *actual* problem you want to solve? What would that string look like and how would it be used? A *meaningful* format would be to use JSON and serialize using eg Json.NET's `JConvert.SerializeObject`. That doesn't make a good `ToString()` format though. – Panagiotis Kanavos Oct 30 '19 at 10:18
  • 1
    `ToString()` is used to display strings in the debugger, eg in watch windows, *when the type has no DebuggerDisplay* attribute. It's far better to add that attribute with the format you want to see instead of overriding `ToString()` – Panagiotis Kanavos Oct 30 '19 at 10:19
  • Check [Tell the debugger what to show using the DebuggerDisplay Attribute](https://learn.microsoft.com/en-us/visualstudio/debugger/using-the-debuggerdisplay-attribute?view=vs-2019) – Panagiotis Kanavos Oct 30 '19 at 10:28

7 Answers7

13

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);
}
Welcor
  • 2,431
  • 21
  • 32
13

You could use JSON.NET to serialize your class.

public override string ToString()
{
    return JsonConvert.SerializeObject(this);
}
Ray Krungkaew
  • 6,652
  • 1
  • 17
  • 28
3

One more additional way not mentioned in the answer is to use following Visual Studio extension: https://marketplace.visualstudio.com/items?itemName=DavideLettieri.AutoToString. Once extension is installed, hit Ctrl + . inside class body, and there will be additional Generate ToString() action available.

AEM
  • 1,354
  • 8
  • 20
  • 30
Daniil Katson
  • 31
  • 1
  • 1
1

There is no equivalent of what you say about Java and Eclipse.

@RawitasKrungkaew answer is good.

If you don't want to use JSON, you can use reflexion with an extension method to have reusability:

In some class

public override string ToString()
{
  return this.GetPropertiesAsText();
}

PropertiesListerHelper.cs

using System.Reflection;

static public class PropertiesListerHelper
{
  static private bool IsProcessing;

  static public string GetPropertiesAsText(this object instance)
  {
    if ( IsProcessing )
      return $"<Reentrancy in {instance.GetType().Name}.ToString()>";
    IsProcessing = true;
    try
    {
      string result = "";
      var list = instance.GetType().GetProperties().OrderBy(item => item.Name);
      foreach ( var property in list )
      {
        var value = property.GetValue(instance);
        result += $"{property.Name} = {(value == null ? "<null>" : value)}, ";
      }
      return result.TrimEnd(", ".ToArray());
    }
    catch ( Exception ex )
    {
      return $"<Exception in {instance.GetType().Name}.ToString(): {ex.Message}>";
    }
    finally
    {
      IsProcessing = false;
    }
  }
}

So the behavior works even if the class design is changing.

You can adapt the method to format the output as you want, for example:

foreach ( var property in list )
{
  var value = property.GetValue(instance);
  result += $"{property.Name} = {(value == null ? "<null>" : value)}"
          + Environment.NewLine;
}
return result.TrimEnd(Environment.NewLine.ToArray());

The management of the case of reentrancy may be improved because it can cause stack overflow on forms for example.

0

There isn't a way to do it by default - what you're seeing in Eclipse is a nicety of Eclipse, rather than built in functionality of the runtime. You can code an extension to VS yourself (check my comment) or you can use an extension that does it. I know that Resharper offers the facility, but I must stress that SO is not a "find me a library that does..." service so I do not offer any endorsement or recommendation of Re# in any way

It might also be worth pointing out that:

  1. You could do this relatively easily in a capable text editor
  2. You could write a small app that generates a tostring upon copying a class to the clipboard
  3. You could drop your desire for it; in c# we don't really use ToString() anywhere near as extensively as java bods do because we've had a wonderful step debugger built into the IDE ever since it was first released. We seldom need to stringify our objects and dump them to a command line to inspect the state of the program's objects at any point, because we can just pause it and see it in the Locals window etc. If you're not fully up to speed with everything the debugger can do for you I recommend taking a look at a few videos
Caius Jard
  • 72,509
  • 5
  • 49
  • 80
-1

I don't think Visual Studio has an action to perform that kind of code generation out of the box. You can however do that with the go-to extension of Visual Studio: JetBrains Resharper.

It has an action for quick ToString generation (along with many, many other features).

https://www.jetbrains.com/help/resharper/Code_Generation__Formatting_Members.html

Alberto Chiesa
  • 7,022
  • 2
  • 26
  • 53
-3

You can do like this:

 public override string ToString()
 {
     return "First name: " + FirstName + ", Last name: " + LastName;
 }

or maybe better solution:

 public override string ToString()
 {
     return nameof(FirstName) + FirstName + ", " nameof(LastName) + LastName;
 }

Use cast on property if it is necessary.

TJacken
  • 354
  • 3
  • 12