65.9K
CodeProject is changing. Read more.
Home

Useful wrapper class to override the Object.ToString method

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Sep 13, 2011

CPOL
viewsIcon

6681

You can write an extension method like this:public static class ToStringExtensionMethod{ public static string ToString(this Person person, bool showName) { return person.Name; }}then you can use it like this:public class Program{ Person person = new...

You can write an extension method like this:

public static class ToStringExtensionMethod
{
    public static string ToString(this Person person, bool showName)
    {
        return person.Name;
    }
}

then you can use it like this:

public class Program
{
    Person person = new Person() { Name = "testName" };
    Console.WriteLine(person.ToString(true));
}

It seems to be a little strange to use the parameter bool showName here, but sometimes it can be useful if you need to print something with options.

P.S.: I don't know whether it works or not in a sealed class. You can try it. ;)

Sorry for my poor English.