What is the difference between cast int for string and ToString () method in C #

What is the difference between distinguishing Int from a string and the ToString () method?

For example: -

int MyInt = 10;
label1.Text = (string)MyInt;       // This Doesn't Work
label1.Text = MyInt.ToString();    // but this does.
+3
source share
6 answers

Well, ToString()it's just a method call that returns a string. It is defined in object, so it is always valid to call anything (other than a null reference).

A cast operator can perform one of four tasks:

  • A predefined conversion, for example. intbeforebyte
  • Converting references to runtimes that may fail, for example. casting objectup stringthat checks if the target is a suitable type
  • ( ),
  • unboxing, , . object int

int string. , .

+20

, , int , .

ToString() int, :)

+9

Um, ToString() , .

, , , ( ), .

, , ( ), , , , .

, , Int32 String.

+1

.ToString() - , System.Object( .NET) .

"int" .ToString(), ints .

(string) myint , / ( int ). , , int .

, , , int , .ToString() , int , !

+1

ToString() , , Java, , Object.

, # :

public override string ToString()

, Object . ​​ , , .

, , ToString , , # - Struct Int32.
Int32 , , ToString().

0
source

One more thing never uses .ToString () if you think the object may be null or your application will judge an example:

// Emulates a problem that may happen
object obj = null; obj.ToString ();

0
source

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


All Articles