Click here to Skip to main content
15,886,578 members
Articles / Programming Languages / C#
Alternative
Tip/Trick

Useful wrapper class to override the Object.ToString method

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
4 Oct 2011CPOL 6.6K  
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:


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

then you can use it like this:


C#
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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
-- There are no messages in this forum --