Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between casting/conversion methods in C#

Tags:

c#

there are many ways to cast/convert object to another by what the difference between those and if there is no difference why there are so many ways to achieve one thing? Isn't that damage to language?

let's say object obj to string.

obj.ToString()
obj as string
(string)obj
Convert.ToString(obj)
like image 376
eugeneK Avatar asked Jul 05 '10 09:07

eugeneK


People also ask

What are the two types of casting in C?

The two types of type casting in C are: Implicit Typecasting. Explicit Typecasting.

What is the difference between implicit type conversion and explicit type conversion?

Implicit conversion is the conversion in which a derived class is converted into a base class like int into a float type. Explicit conversion is the conversion that may cause data loss. Explicit conversion converts the base class into the derived class.

What is type casting and type conversion in C with example?

Type casting refers to changing an variable of one data type into another. The compiler will automatically change one type of data into another if it makes sense. For instance, if you assign an integer value to a floating-point variable, the compiler will convert the int to a float.

What are the different types of conversion?

There are two types of conversion: implicit and explicit. The term for implicit type conversion is coercion. Explicit type conversion in some specific way is known as casting. Explicit type conversion can also be achieved with separately defined conversion routines such as an overloaded object constructor.


1 Answers

You are doing different things here:

  • obj.ToString() - this is a call to the ToString() method of the object. The object returns a string as it was programmed to.
  • obj as string - this is an attempt to convert the object to a string, which may or may not fail (if it fails, the result is null), no exception will be thrown.
  • (string)obj - this is an explicit cast of obj to the type string, you are telling the compiler that obj is a string. If obj is not a string type, you will get a cast exception.
  • Convert.ToString(obj) - This is an explicit call to the Convert class to return a string representation of obj.

There are these many different ways to get a string from an object because each one is different and have subtle differences. Yes, in many cases the returned string will be the same, but this is not guaranteed.

like image 139
Oded Avatar answered Oct 13 '22 04:10

Oded