Type casting is changing a variable from one type to another, e.g. from
float
to
int
.
You'd use it when you have an object of one type but you need it to be another, but it is often handled for you, for example if you used
String.Format("{0} {1} {2}", 1, 2.3, "four");
String.Format
is expecting a
string
and 3
object
s, but it was given a
string
, an
int
, a
float
, and another
string
instead, so the last 3 arguments are cast to
object
s instead.
Another time would be if an object explicitly implements an interface, it must be cast to that interface before the interface's methods can be used.
Like in this case:
class IntComparer : IComparer<int>
{
int IComparer<int>.Compare(int x, int y)
{
return x.CompareTo(y);
}
}
If you made an object of type
IntComparer
, the
Compare
method is only available if you cast it to an
IComparer<int>
first, like this:
IntComparer c = new IntComparer();
c.Compare(1,2);
((IComparer<int>)c).Compare(1,2);