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();
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.
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.
To convert an integer to string in C#, use the ToString() method.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With