What is the difference between xxx.tostring () and (string) xxx?

What is the difference in the two string methods below?

string str1 = dr["RAGStatusCID"].ToString();
string str2 = (string)dr["Description"];
+3
source share
8 answers

In short, .toString()this is a method, like any other, (String)is a translation, a language construct used to process one data type as another compatible type.

Now for some details:

.toString() - , , . "" - , , , , . Object, , . , . # . , , , , , , .

, , , ToInt(), ToDouble() ToChar(), .

- , , . , , .

0

, dr. ToString, indexer dr["RAGStatusCID"]. dr["Description"] .

, dr SqlDataReader, , , Description .

+5

dr , , , , .

get dr ToString() , , , . , .

, , System.String. System.String, , . , System.String. ( ) MSDN.

+4

, . - ToString. - .

+3
string str1 = dr["RAGStatusCID"].ToString(); 

.ToString() , dr["RAGStatusCID"]. .

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

, dr["Description"] . , .

+2

xxx.ToString() , . (string)xxx , . , , .

, RagStatusCID , (string) dr [ "RagStatusCID" ], , , int. .ToString() , - .

0

(string) - casting operation .. ToString () - a method that inherits from the Object class. Everyone has .ToString (), but not everyone has (string). In addition, some objects will distinguish a string other than that .ToString ().

0
source

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

(String)myinstanceimplicitly calls the implementation .toString()of the myinstance 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 + ")";
      }
}

using the method toStringyou determine what (String)instancecasting does

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

will print "Username: Alex (22)"

0
source

Source: https://habr.com/ru/post/1787531/


All Articles