Sunday, January 27, 2008

Override ToString()

.Net IDE provides excellent support for debugging. One of the supporting tools is the Watch window. It does a very good job when it comes to displaying of data, but it doesn't always display the data in the best form, especially for the classes that we write. But that is not the fault of the Watch window, its we the developers who are not providing correct implementation of ToString() to our classes.

The .net debugger calls the ToString() automatically on the instance which is to be monitored in the watch window. If we override the ToString() implementation in our class and provide the key fields as part of implementation, that will make our job a lot easier when it comes to debugging.

See the following code listing. Run it with the ToString() method commented and add a instance of the clsExample class nin watch window and notice the data. Compare it with the original verison.


using System.Diagnostics;

namespace DebuggererAttribute

{

public class clsExample

{

private int _FieldOne;

private double _FieldTwo;

private string _FieldThree;

private bool _FieldFour;

public int FieldOne

{

get

{

return _FieldOne;

}

set

{

_FieldOne = value;

}

}

public double FieldTwo

{

get

{

return _FieldTwo;

}

set

{

_FieldTwo = value;

}

}

public string FieldThree

{

get

{

return _FieldThree;

}

set

{

_FieldThree = value;

}

}

public bool FieldFour

{

get

{

return _FieldFour;

}

set

{

_FieldFour = value;

}

}

public override string ToString()

{

return string.Format("FieldOne = {0}, FieldTwo = {1}, FieldThree = {2}, FieldFour = {3}", _FieldOne, _FieldTwo, _FieldThree, _FieldFour);

}

public clsExample()

{

_FieldOne = 2;

_FieldTwo = 3.66;

_FieldThree = "This is some text";

_FieldFour = true;

}

}

}

No comments: