40

Is there any way to generate a ToString() using Visual Studio 2010?

I really don't want to do this by hand!

[EDIT]

I'm looking for a simple string representation of my model. In previous IDEs * ToString generation has been enabled in the UI using simple templates and field selection.

Currently default implementations of Equals and Hashcode are offered in a similar pattern. I'd hoped there was something similar for ToString.

It seems not by default - thanks for the responses!

(* this is my first .net project)

laura
  • 2,951
  • 9
  • 44
  • 61
  • 1
    On what basis it should generate the string representation ? – anthares Feb 08 '11 at 10:54
  • 1
    There is in ReSharper, I havent user VS without it so I really dont know if there is one;) – Eduard Feb 08 '11 at 10:56
  • 1
    Do you mean an `override`? If so then simply type `override`, space and select `ToString` from the list - it will generate the method body for you. – Jaroslav Jandek Feb 08 '11 at 10:58
  • @anthares I'd hoped there was something similar to Equals generation - where the fields are made available for selection. – laura Feb 08 '11 at 10:58
  • @lainie - can you edit the question and explain what you mean? What is there for `Equals`? – Kobi Feb 08 '11 at 11:01
  • You probably need a snippet as the answer below suggests – anthares Feb 08 '11 at 11:02
  • 1
    @lainie, I'm with you on this one. We are both looking for some stupid-simple ToString generator like Eclipse: http://wiki.eclipse.org/ToString()_generation. I don't think too many .NETers are familiar with this kind of feature. – Richard Clayton Mar 22 '11 at 02:02
  • 1
    It is a pity that VS2010 is not so smart as IntelliJ IDEA even of the first versions. Maybe, it is because that overriding ToString() is not so popular in .NET as in Java. – meir Oct 13 '11 at 09:52
  • For the year 2020. And VS 2019/2017. (for people who stumble onto this old question). https://marketplace.visualstudio.com/items?itemName=DavideLettieri.AutoToString DavideLettieri.AutoToString – granadaCoder Jun 24 '20 at 14:15

11 Answers11

26

Resharper supports this by generating "formatting members"

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

Resharper -> Edit -> Generate Code -> Formatting Members

or

alt + insert -> Formatting Members

I confirmed this is available in Resharper 8.

tster
  • 17,883
  • 5
  • 53
  • 72
10

With Reflection you can actually code a ToString() method:

public override String ToString()
{
    Type objType = this.GetType();
    PropertyInfo[] propertyInfoList = objType.GetProperties();
    StringBuilder result = new StringBuilder();
    foreach (PropertyInfo propertyInfo in propertyInfoList)
         result.AppendFormat("{0}={1} ", propertyInfo.Name, propertyInfo.GetValue(this));

     return result.ToString();
}
derloopkat
  • 6,232
  • 16
  • 38
  • 45
J Roig
  • 111
  • 1
  • 3
  • 3
    Uggg Reflection and application performance. ToString methods should execute as fast as possible. – Andrew Mar 15 '19 at 20:34
6

You can use the StatePrinter project

class AClassWithToString
{
  string B = "hello";
  int[] C = {5,4,3,2,1};

  // Nice stuff ahead!
  static readonly StatePrinter printer = new StatePrinter();
  public override string ToString()
  {
    return printer.PrintObject(this);
  }
}
Carlo V. Dango
  • 13,322
  • 16
  • 71
  • 114
  • I think this is a good suggestion and gave it an upvote. However, beware anyone who is trying to do this from VB rather than C#: http://stackoverflow.com/q/35092412/165164 – Anne Gunn Jan 31 '16 at 00:10
4

You can create your own custom snippet for every boilerplate code and access it from IntelliSence
Here is a good tutorial http://msdn.microsoft.com/en-us/library/ms165392.aspx

Have a good look at how to create snippets with replacements. You can create quite generic structures.

Mr. L
  • 3,098
  • 4
  • 26
  • 26
  • 10
    I have no idea why this solution was accepted. It provides, at best, tangentially related information. Snippets do not have the power to do what the OP requests. – Eric Haynes Apr 11 '16 at 06:48
4

Major pain that VS 2010 doesn't even have an autogenerate ToString method, syntax is close enough to Java where I used Ecilpse to Generate the ToString and then pasted it into VS...

4

It doesn't exist on VS out of the box, but it does on the ReSharper plugin, if you don't want to implement it yourself. The plugin is commercial, but I personally think it is worth the money.

With ReSharper, it would be alt+ins -> overriding members -> tostring while class name is on the cursor.

eis
  • 51,991
  • 13
  • 150
  • 199
  • alt+ins -> formatting members also generates a ToString in R# 7.1. ReSharper is an indispensable tool. – Travis Jan 19 '14 at 17:34
3

Maybe you should take a look at AutoCode 4.0. It is a Visual Studio extension which will brings some snippets with it.

For example you could somewhere within your class simply write tostr and press Ctrl+Enter and it will automatically generate the ToString() method that concatenates all public properties of the class.

Oliver
  • 43,366
  • 8
  • 94
  • 151
2

If you need better representation of your object while debugging you can use the DebuggerDisplayAttribute:

[DebuggerDisplay("Count = {count}")]
class MyHashtable
{
    public int count = 4;
}

This can be quicker than overriding ToString, but it still doesn't let you choose fields, you have to type them.

Kobi
  • 135,331
  • 41
  • 252
  • 292
0

If you don't write your own ToString method, Object provides one for you (although not very useful, since it only return the namespace and name of the objects type).

Otherwise, you have to create it yourself, since the IDE cannot possibly know what you want to output as an object's ToString method.

Øyvind Bråthen
  • 59,338
  • 27
  • 124
  • 151
-3

Since the logic of the overridden ToString() method would depend on your own business needs, the only thing I could imagine is an add-in which creates the empty ToString() override for you calling base.ToString() inside, if you then do not customize its content it does not make any sense to have it like that.

Visual Studio already helps you a lot, at least in C#, if you start typing public overrides.

Rubens Mariuzzo
  • 28,358
  • 27
  • 121
  • 148
Davide Piras
  • 43,984
  • 10
  • 98
  • 147
  • 2
    you don't even have to write `public`. If you start with override and select the `ToString` method from the dropdown, public will be added automatically. – Øyvind Bråthen Feb 08 '11 at 10:59
  • 5
    "only thing I could imagine"... how about the local variables printed out like Eclipse does? I don't see how that would be beyond imagination. – eis Jun 04 '13 at 07:16
-3

ToString() is a method sitting on object so you do not need to add that to all your classes, only if you need to override and change behaviour.

Aliostad
  • 80,612
  • 21
  • 160
  • 208
  • 5
    It seems like you missed the point. Lainie is asking if VS will auto-generate the method like Eclipse and NetBeans. You can't always rely on having a debugger present, and being able to dump the state of the object to a log is essential. – Richard Clayton Mar 22 '11 at 01:58