Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between .ToString and "as string" in C#

What is the difference between using the two following statements? It appears to me that the first "as string" is a type cast, while the second ToString is an actual call to a method that converts the input to a string? Just looking for some insight if any.

Page.Theme = Session["SessionTheme"] as string; Page.Theme = Session["SessionTheme"].ToString(); 
like image 676
jaywon Avatar asked Jan 20 '10 08:01

jaywon


People also ask

What is the difference between ToString and string?

Both these methods are used to convert a string. But yes, there is a difference between them and the main difference is that Convert. Tostring() function handles the NULL while the . ToString() method does not and it throws a NULL reference exception.

What is the difference between string and ToString in C#?

Both these methods are used to convert a value to a string. The difference is Convert. ToString() method handles null whereas the ToString() doesn't handle null in C#. In C# if you declare a string variable and if you don't assign any value to that variable, then by default that variable takes a null value.

How do I convert a number to a string in C#?

To convert an integer to string in C#, use the ToString() method.

What is ToString in C?

ToString is the major formatting method in the . NET Framework. It converts an object to its string representation so that it is suitable for display.


1 Answers

If Session["SessionTheme"] is not a string, as string will return null.

.ToString() will try to convert any other type to string by calling the object's ToString() method. For most built-in types this will return the object converted to a string, but for custom types without a specific .ToString() method, it will return the name of the type of the object.

object o1 = "somestring"; object o2 = 1; object o3 = new object(); object o4 = null;  string s = o1 as string;  // returns "somestring" string s = o1.ToString(); // returns "somestring" string s = o2 as string;  // returns null string s = o2.ToString(); // returns "1" string s = o3 as string;  // returns null string s = o3.ToString(); // returns "System.Object" string s = o4 as string;  // returns null string s = o4.ToString(); // throws NullReferenceException 

Another important thing to keep in mind is that if the object is null, calling .ToString() will throw an exception, but as string will simply return null.

like image 63
Philippe Leybaert Avatar answered Sep 17 '22 19:09

Philippe Leybaert