Casting vs Convert object toString when the object is really a string

This is not a problem, but I'm curious. When I store a string in let, say, a DataRow, it is passed to the object. When I want to use it, I have to use its ToString. As far as I know, there are several ways to do this, first

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

and the other:

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

I'm interested in what is the difference between the two? Is the first one more efficient? (This is just an assumption; in my head, the ToString () method is implemented by some kind of loop mechanism in which only "casting" can "be faster, but it's just the" gut feeling "that I have).

Is there an even faster / more elegant way to do this?

Can anyone clarify this for me?

+64
string casting c # parsing
Jul 23 '09 at 9:58
source share
9 answers

Both are for different purposes. The ToString method of any object should return a string representation of this object. Casting is completely different, and the key β€œhow” the word performs conditional casting, as it was said. The "how" keyword basically says: "Get me a reference of this type to this object, if it is an object - this is the type" while ToString says: "Get a string representation of this object." The result may be in some cases, but they are never considered interchangeable because, as I said, they exist for different purposes. If your intention is to quit, then you should always use cast, NOT ToString.

from http://www.codeguru.com/forum/showthread.php?t=443873

see also http://bytes.com/groups/net-c/225365-tostring-string-cast

+46
Jul 23 '09 at 10:06
source share

If you know that it is String , then, in any case, discard it on String . Casting your object will be faster than calling a virtual method.

Edit: Below are some benchmarking results:

 ============ Casting vs. virtual method ============ cast 29.884 1.00 tos 33.734 1.13 

I used Jon Skeet BenchmarkHelper as follows:

 using System; using BenchmarkHelper; class Program { static void Main() { Object input = "Foo"; String output = "Foo"; var results = TestSuite.Create("Casting vs. virtual method", input, output) .Add(cast) .Add(tos) .RunTests() .ScaleByBest(ScalingMode.VaryDuration); results.Display(ResultColumns.NameAndDuration | ResultColumns.Score, results.FindBest()); } static String cast(Object o) { return (String)o; } static String tos(Object o) { return o.ToString(); } } 

So, it seems that casting is actually a little faster than calling ToString() .

+27
Jul 23 '09 at 10:01
source share

Basically in your case it is better to leave the type, because .ToString () can hide errors. For example, your database schema has changed and the name no longer has a string type, but with .ToString () your code still works. Therefore, in this case, it is better to use the cast type.

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

 public override string ToString() { return this; } 
+16
Jul 23 '09 at 10:04
source share

Downcasting is a relatively slow operation since the CLR must perform various checks such as runtime. However, in this particular scenario, casting to string more appropriate than calling ToString() for consistency (you cannot call ToInt32 on an object , but drop it to int ) and maintanability.

+5
Jul 23 '09 at 10:04
source share

I want to make another comment

If you intend to use casting: string name = (string) DataRowObject ["name"] you will get an exception: it is impossible to cast an object of type "System.DBNull" on type'System.String if the entry in the database table has a null value.

In this scenario, you should use: string name = DataRowObject ["name"]. ToString () or

You should check for a null value like

 if(!string.IsNullOrEmpty(DataRowObject["name"].ToString())) { string name = (string)DataRowObject["name"]; } else { //ie Write error to the log file string error = "The database table has a null value"; } 
+4
Jul 30 '09 at 17:43
source share

In this case:

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

since this is a string , I think the ToString() method of the string object is simple as:

 return this; 

therefore IMHO there is no penalty for performance.

PS I am a Java programmer, so this anwser is just a guess.

+2
Jul 23 '09 at 10:07
source share

For a data object, I suggest you use the keyword "how", for example, the following code.

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

Please check it before using the value.

 if(name != null) { // statement for empty string or it has value } else { // statement for no data in this object. } 
+2
Jul 23 '09 at 10:11
source share

ToString () does not throw by default. Its purpose is to return a string representing the type (for example, "System.Object").

If you want to avoid casting, you can try to think of an implementation that is strongly typed (for example, using generics) and generally avoids DataRowObject.

+1
Jul 23 '09 at 10:11
source share

I know that you mentioned that Object is a string, but if you are afraid that the returned object is null, you can also use the command "Convert.ToString (DataRowObject [" name "]); This gives an additional advantage when returning an empty string (string.empty) if the object is NULL to exclude null reference exceptions (unless, of course, you do not want an exception in such cases).

0
Apr 11 '13 at
source share



All Articles