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 s
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...
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.
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.
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.
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();
}