Casting vs Converting an object toString, when object really is a string

C#StringCastingParsing

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

> The two are intended for different > purposes. The ToString method of any > object is supposed to return a string > representation of that object. Casting > is quite different, and the 'as' key > word performs a conditional cast, as > has been said. The 'as' key word > basically says "get me a reference of > this type to that object if that > object is this type" while ToString > says "get me a string representation > of that object". The result may be the > same in some cases but the two should > never be considered interchangeable > because, as I said, they exist for > different purposes. If your intention > is to cast then you should always use > a 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

Solution 2 - C#

If you know it is a String then by all means cast it to a String. Casting your object is going to be faster than calling a virtual method.

Edit: Here are the results of some benchmarking:

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

I used Jon Skeet's BenchmarkHelper like this:

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 appears that casting is in fact slightly faster than calling ToString().

Solution 3 - C#

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;
}

Solution 4 - C#

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 calling ToString() for the sake of consistency (you can't call ToInt32 on object, but cast it to int) and maintanability.

Solution 5 - C#

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

if(!string.IsNullOrEmpty(DataRowObject["name"].ToString()))
{
string name = (string)DataRowObject["name"];
}
else
{
//i.e Write error to the log file
string error = "The database table has a null value";

}

Solution 6 - C#

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.    
}

Solution 7 - C#

In this case:

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

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

return this;

so IMHO there is no performance penalty.

PS I'm a Java programmer, so this anwser is only a guess.

Solution 8 - C#

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.

Solution 9 - C#

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).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDavid BožjakView Question on Stackoverflow
Solution 1 - C#Adriaan StanderView Answer on Stackoverflow
Solution 2 - C#Andrew HareView Answer on Stackoverflow
Solution 3 - C#Dzmitry HubaView Answer on Stackoverflow
Solution 4 - C#Anton GogolevView Answer on Stackoverflow
Solution 5 - C#SergoTView Answer on Stackoverflow
Solution 6 - C#user94893View Answer on Stackoverflow
Solution 7 - C#dfaView Answer on Stackoverflow
Solution 8 - C#martijn_himselfView Answer on Stackoverflow
Solution 9 - C#n00bView Answer on Stackoverflow