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

c#, string, tostring

Solution

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`.

Problem

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(); ```

Original source

Related problems