What is the difference between using ivariable.ToString() and (string)ivariable? My understanding is that (string)ivariable is recasting the variable. But how does that differ from ToString()?
Thank you for any help.
2 Replies - 328 Views - Last Post: 27 October 2012 - 01:37 PM
#1
What is the difference between .ToString() and (string)variable?
Posted 27 October 2012 - 01:13 PM
Replies To: What is the difference between .ToString() and (string)variable?
#2
Re: What is the difference between .ToString() and (string)variable?
Posted 27 October 2012 - 01:18 PM
.ToString() is a method within the class - That's why you see parenthesis.
If you make a custom class (possibly inherited from another class) .NET won't know how to implicitly convert it to a string. So you make (or override) the .ToString() method to provide the exact string you want to return fro your class.
If you make a custom class (possibly inherited from another class) .NET won't know how to implicitly convert it to a string. So you make (or override) the .ToString() method to provide the exact string you want to return fro your class.
public class Widget
{
public string ToString()
{
// Do some fancy work calculating some value
// And adding other strings together
return myFancyCalculatedString;
}
}
#3
Re: What is the difference between .ToString() and (string)variable?
Posted 27 October 2012 - 01:37 PM
.ToString has nothing to do with casts. A cast is a an operator.
.ToString() is more to do with a textual representation of the information in the object, which why it also has an overloads that takes a IFormatProvider and a FormatString. By default it inherits the .ToString from its base class, and ultimately all object inherit from type Object, which provide (through reflection i think.) the fully qualified name of the object. eg. System.Linq.Enumerable.
public static explicit operator Int64(dbInt64 x)
{
}
public static implicit operator Int64(dbInt64 x)
{
}
.ToString() is more to do with a textual representation of the information in the object, which why it also has an overloads that takes a IFormatProvider and a FormatString. By default it inherits the .ToString from its base class, and ultimately all object inherit from type Object, which provide (through reflection i think.) the fully qualified name of the object. eg. System.Linq.Enumerable.
This post has been edited by AdamSpeight2008: 27 October 2012 - 01:38 PM
Page 1 of 1
|
|

New Topic/Question
Reply



MultiQuote





|