3

whats the difference in the two string methods below?

string str1 = dr["RAGStatusCID"].ToString();
string str2 = (string)dr["Description"];
2
  • 1
    possible duplicate of [What's the difference between casting an int to a string and the ToString() method in C# ](stackoverflow.com/questions/709263/…)
    – BoltClock
    Jan 24, 2011 at 19:53
  • the result is identical since (strings) is a implicit call to ToString()
    – skyline26
    May 12, 2012 at 22:52

8 Answers 8

5

This will depend on what dr is. The first invokes the ToString method that each object could override on the indexer of the dr["RAGStatusCID"]. The second casts the dr["Description"] variable to a string.

If we use our telepathic skills and suppose that dr is a SqlDataReader then the two expression do pretty much the same thing except that the cast might throw an exception at runtime if the Description column is not a string.

0
5

You haven't mentioned the type of dr or what it's indexer operation returns, but ostensibly, these are two very different operations.

The first invokes the get indexer of dr and calls the ToString() method on the returned reference, allowing the object that reference refers to to provide a string representation of it's data. The generial intent of this is to allow the object itself to return a meaningful representation of itself as a string.

The second call attempts to cast the reference returned by the indexer to System.String. The object returned must either be an instance of System.String or must be a type that the compiler can invoke a custom conversion operator on. Here, the intent is to ensure that the object returned can be treated as an instance of System.String. You can read more about conversions (including user-defined ones) on MSDN.

1
  • Nice answer. Would be nice to have a link to C# conversions though.
    – user166390
    Jan 24, 2011 at 21:00
3

First one calls the method that returns the string. Someone has to implement ToString method. Second one is just unboxing.

1
2
string str1 = dr["RAGStatusCID"].ToString(); 

This calls the .ToString() method on the object returned from the dr["RAGStatusCID"] call. It is guaranteed to return a string or null.

string str2 = (string)dr["Description"]; 

This attempts to cast the object returned by dr["Description"] to a string. If the object returned is not a string, then an exception is thrown.

0

in short, .toString() is a method, just like any other, (String) is a cast, a language construct used to treat one data type as another, compatible type.

Now for some detail:

.toString() is a method, just like any other method you may encounter. Its often thought to be a 'special' method in some way, but it isnt really, all it does is return a string. because its a member of the base Object type, it can be relied upon to be available in every object. For this reason it is generally used to provide a textual representation of the object of which it is member. By default, in c# this is the name of the type of the object. It is often desirable to override this method to provide a more meaningful name, but all it needs to do is return a string, this can be any string you like.

As noted before, theres nothing special about it, and you could just as easily have methods called ToInt(), ToDouble(), and ToChar() to provide the same functionality for there respective types.

Casting is a language construct, this means its built into the language and is implemented specifically for that language. It is used to enable compatible but different types to be used in different locations without the need for an explicit conversion.

1
  • 3
    This isn't ... correct -- see other answers. C# supports both user-defined implicit and explicit conversions. The type being converted (object here) needs to be taken into account -- in this case it really just a "plain-old-cast". Note that barring any conversions only something that is a string or a subclass of a string "can be treated like one". (string)(object)42 fails no matter how much it would be nice if it didn't :-/
    – user166390
    Jan 24, 2011 at 20:56
0

xxx.ToString() calls a method on that object to convert it into a string object. (string)xxx assumes that the type of the object is already a string and simply performs a cast on the existing object. So in the first case a conversion happens, in the second it's just identifying the type explicitly.

To put it more succinctly, if in your example RagStatusCID is an integer and you attempted to call (string)dr["RagStatusCID"] you would get an exception because the type is not a string, it's an int. Calling .ToString() performs a conversion and the output is a string.

0

(string) is a casting operation. .ToString() is a method that is inherited from the Object class. Everything has a .ToString(), but not everything has a (string). Additionally certain objects will cast to a string different than the one .ToString() outputs.

0

I don't know if it is correct for C# but it probably is, so:

(String)myinstance calls implicitly the .toString() implementation of myinstance's class

if you have a class like this:

class User
{
      private integer userId;
      private integer userName;
      ... some code here...
      public toString()
      {
           return "Username: " + this.userName + " (" + this.userId + ")";
      }
}

with the method toString you are defining what (String)instance casting will do

User myuser = new User("Alex", 22);
String myuserdump = (String)myuser;
print(myuserdump);

will print "Username: Alex (22)"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.