Casting vs Converting an object toString, when obj

2019-01-06 11:31发布

This isn't really an issue, however I am curious. When I save a string in lets say an DataRow, it is cast to Object. When I want to use it, I have to cast it ToString. As far as I know there are several ways of doing this, first is

string name = (string)DataRowObject["name"]; //valid since I know it's a string

and another one is:

string name = DataRowObject["name"].ToString();

I am interested in what is the difference between both? Is the first more efficient? (This is just a speculation, in my head ToString() method is implemented by some looping mechanism where just casting it "could" be faster, however this is just a "gut feeling" I have).

Is there even a faster / more elegant way of doing this?

Can anyone clear this up for me?

9条回答
趁早两清
2楼-- · 2019-01-06 12:26

I know you mentioned that the Object is a string, but incase you're afraid that the returned object is null, you can also cast using "Convert.ToString(DataRowObject["name"]);" This has the added benefit of returning an empty string (string.empty) if the object is null, to avoid any null reference exceptions (unless of course you want an exception thrown in such cases).

查看更多
来,给爷笑一个
3楼-- · 2019-01-06 12:31

Basically in your case it is better to leave type cast because .ToString() may hide bugs. For example, your data base schema changed and name is no longer of string type but with .ToString() your code still works. So in this case it is better to use type cast.

Here is implementation of String.ToString() - nothing special =)

public override string ToString()
{
    return this;
}
查看更多
Summer. ? 凉城
4楼-- · 2019-01-06 12:33

For data object, I suggest you to use "as" keyword like the following code.

string name = DataRowObject["name"] as string;

Please check it before you use value.

if(name != null)
{
    // statement for empty string or it has value
}
else
{
    // statement for no data in this object.    
}
查看更多
登录 后发表回答