2

I am trying to use an extension method to implement ToString() in a class that doesn't have it. If I change the method declaration to ToString2(), it works fine, but when I try to use .ToString it fails. Why does ToString2() work, but not ToString()?

Error:

System.NullReferenceException: Object reference not set to an instance of an object.

Here's my method implementation:

namespace LeankitExtensions
{
    public static class CardViewExt
    {
        public static string ToString(this CardView c)
        {
            if (c == null)
                return "null card";

            return String.Format("-------\nexternal id: {0} \ntitle: {1}\n-------",c.ExternalCardID,c.Title);
        }
    }
}

Calling the method:

CardView cv = new CardView(){ExternalCardID="22";Title="Hi"};
Console.WriteLine(cv.ToString());
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Rilcon42
  • 9,584
  • 18
  • 83
  • 167

2 Answers2

3

Because ToString() is a method of class Object, if you want to use the method name ToString() you need to override the base class's version of it. You are not going to be able to make an extension method called ToString() since one already exists in the base class Object. If you wanted to do this as an extension method, call it something like CardViewToString()

Ryan Wilson
  • 10,223
  • 2
  • 21
  • 40
2

Every class in C# is by default inherited from the Object class which has some methods three of which we can override which are ToString(), Equals() and GetHashCode().

Now the problem with your code is that instead of overriding ToString() method in your CardView class, you are creating extension method. What you should do is to override the ToString() method in CardView class as I have shown in the below code.

    public override string ToString()
    {

        //if (this == null) -- Not needed because the ToString() method will only be available once the class is instantiated.
        //    return "null card";

        return String.Format("-------\nexternal id: {0} \ntitle: {1}\n-------", this.ExternalCardID, this.Title);
    }

However if the CardView class is in some DLL which you cannot edit, I would suggest you create an extension method with some other name just like shown below.

public static class CardViewExt
{
    public static string ToStringFormatted(this CardView c)
    {
        if (c == null)
            return "null card";

        return String.Format("-------\nexternal id: {0} \ntitle: {1}\n-------", c.ExternalCardID, c.Title);
    }
}