C #: Force compiler error when using myObj.ToString ()

I have a class containing a bunch of properties. This is a programmer error if they call ToString () on an object of this type. Take this sample code:

using System;

public class Foo
{
    public int ID = 123;
    public string Name = "SomeName";

    private string ToString() { return null; }
}

public class MyClass
{
    public static void Main()
    {
        Foo myObj = new Foo();
        WL("I want this to be a compiler error: {0}", myObj.ToString());
        RL();
    }

    #region Helper methods

    private static void WL(object text, params object[] args)
    {
        Console.WriteLine(text.ToString(), args);   
    }

    private static void RL()
    {
        Console.ReadLine(); 
    }

    #endregion
}

You can assume that if the ID is what most people want to write as a string, then I have to implement ToString so that it returns the identifier. However, I think this is bad practice because programmers will "accidentally" get working code. The programmer using my class should indicate what they want.

Instead, I would like someone to call myObj.ToString () so that this displays as a compile-time error. I thought I could do this by creating a private ToString () function, but that would not work.

, , , , , .

, : "" ToString(), ?

+5
7

, .

ToString() .Net. , . ?

, , - ToString().

:

  • , , , ToString() ? ? , ToString() . ToString(). ToString() - , . .

  • ToString() - , , , . , , - , , . , . , ? ?

  • IDE , ToString()?

  • , , , ? ToString() , .

+44

Obsolete .

[Obsolete("Use the XYZ properties instead of .ToString() on Foobar", true)]

, .

+20

Obsolete .

ToString(), Obsolete:

    [Obsolete("dont' use", true)]
    public override string ToString()
    {
        throw new Exception("don't use");
    }

: 1 ClassLibrary1.Foo.ToString() ' .ToString()' d:\source\ClassLibrary1\ClassLibrary1\Class1.cs 11 32 ClassLibrary1

, . , . , - ToString()? , ToString() :

        Foo myObj = new Foo();

        Console.WriteLine(myObj);

, , . , , , .net.

: , . , , , int, , URL- querystring, id int. , - . , :

public string CreateItemUrl(int itemId)
{
   return string.Format("someurl.aspx?id={0}", itemId);
}

, :

CreateItemUrl(myObj.Id);

, :

string theUrl = string.Format("someurl.aspx?id={0}", myObj);
+7

. (, ?:))

ToString, void. , , - :

public new void ToString() { }

Obsolete, , , , ToString .

ToString , - . , , , .

, , , . , ToString , , , ToString .

: , ToString. " ", . "" , , .

+7

override ToString(), Method.Object ToString().

+1

ToString, string.Empty, . , ToString, , this.GetType(), .

ToString , complier , .

+1

, , /:)

, Foo.ToString Object.ToString(), , "" , . "". IMHO, .

Foo.ToString, , "this" Foo , ((object) foo). ToString() , ToString - Object.

Also, preventing a ToString call is undesirable since Debugger uses it to represent a value. SY, Jake

0
source

All Articles