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?
ToString() does not perform a cast by default. Its purpose is to return a string that represents the type (e.g. "System.Object").
If you want to avoid casting you could try to think of an implementation that is strongly typed (using generics, for example) and avoids DataRowObject altogether.
Downcasting is a relatively slow operation since CLR has to perform various runtime type-checks. However, in this particular scenario casting to
string
is more appropriate than callingToString()
for the sake of consistency (you can't callToInt32
onobject
, but cast it toint
) and maintanability.I want to make one more comment
If you are going to use casting: string name = (string)DataRowObject["name"] you will get an Exception: Unable to cast object of type 'System.DBNull' to type'System.String' in case if the record in the database table has null value.
In this scenario you have to use: string name = DataRowObject["name"].ToString() or
You have to check for null value like
from http://www.codeguru.com/forum/showthread.php?t=443873
see also http://bytes.com/groups/net-c/225365-tostring-string-cast
If you know it is a
String
then by all means cast it to aString
. Casting your object is going to be faster than calling a virtual method.Edit: Here are the results of some benchmarking:
I used Jon Skeet's
BenchmarkHelper
like this:So it appears that casting is in fact slightly faster than calling
ToString()
.In this case:
since it is a
string
, I think that theToString()
method of a string object is simple as:so IMHO there is no performance penalty.
PS I'm a Java programmer, so this anwser is only a guess.