简体   繁体   中英

Difference Between ToString() and Casting to String

string id = (string)result.Rows[0]["Id"];

Above line of code returns InvalidCastException . Why it is that so?

But if I change the code to this

string id = result.Rows[0]["Id"].ToString();

then it's working. Am I did anything wrong in my previous line of code?

it's not working because ID has a different Type. It's not string - so you can convert it but not cast it.

Let's have a look at different operations like if it's some dialog between you and compiler:

    // here you say to compiler "hey i am 100% sure that it is possible 
    // to cast this `result.Rows[0]["Id]` to string
    // this results in error if cast operation failed

    string id = (string)result.Rows[0]["Id"];


    // here you say to compiler: "please try to cast it to 
    // string but be careful as i am unsure that this is possible"
    // this results in `null` if cast operation failed

    string id = result.Rows[0]["Id"] as string;


    // here you say to compiler: "please show me the string representation of 
    // this result.Rows[0]["Id"] or whatever it is"
    // this results in invoking object.ToString() method if type of result.Rows[0]["Id"]  
    // does not override .ToString() method.

    string id = result.Rows[0]["Id"].ToString();

I guess your rows' indexer's type isn't string . A cast looks like this:

(TypeA)objB

This is only successful when

  1. objB is of type TypeA ,

  2. objB is of type TypeC where TypeC is a subclass of TypeA ,

  3. objB is of type TypeC where TypeC is a superclass of TypeA and objB's declaring type is TypeA .

So, your code doesn't work.

However , since every type derives from the holy Object class, every type has a ToString method. Thus, whatever type Rows[0]["Id"] returns, it has or has not a custom implementation of the ToString method. The type of the return value of the ToString method is always, you guessed it, String . So that's why ToString works.

ToString() does not simply cast your object, it calls its ToString -method providing a "string-representation". Casting however means that the object itself IS a string and therefor you can cast it.

Also have a look here: Casting to string versus calling ToString

EDIT: The ToString -method derived from object can be used to give a representation of any arbitrary object.

MyClass 
{
    int myInt = 3;
    public override string ToString() {
        return Convert.ToString(myInt);
    }
}

If ToString is not overridden within your class, than it´s default return-value is the class´ typename.

使用ToString(),您可以将row0的ID转换为字符串,但在其他情况下,则将其转换为字符串,这在当前情况下是不可能的。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM