A couple of days ago I discussed overriding System.Object.Equals(Object obj) in a post called Object Identity vs. Object Equality – Overriding System.Object.Equals(Object obj). The gist of that post is essentially that when you create new classes that inherit from System.Object, you may want to consider overriding System.Object’s virtual methods so that they make sense for your class. In that article we had overriden Equals and GetHashCode for the Customer class to suit our needs for equality.
In continuing this idea, System.Object also has a virtual ToString() method that we inherit in our classes. I find this an absolute must to override, because the method provided by System.Object only returns the name of the class. Hence the output of the following code will just be “Person.”
That is pretty useless for debugging or anythine else. By simply overriding ToString(), we can get something a bit more useful. When we run the new version of our code shown below, we get the following output: “David Hayden, Age = 99″.
So now we are cooking. However, in the real world, we need way more flexibility in how we want to display this person. This is where the interface IFormattable comes in. IFormattable is as basic as you can get. It has one method:
By having our person class implement IFormattable, we can display this person class in a multitude of formats:
The code is fairly straight forward. Let’s forget about formatProvider for this post and just focus on the switch(format) statement. The statment essentially just returns a different result based on the value of format. Format “G” is used by the .NET framework, so just include it for completeness.