Click here to Skip to main content
15,883,883 members
Please Sign up or sign in to vote.
2.50/5 (4 votes)
See more:
Can anyone clear my doubt.
What is Type Casting and where we have to use it?
Posted

This may be a bit more understandable article on casting: http://www.dotnetperls.com/cast[^]
 
Share this answer
 
Conversion between different data types can be done explicitly using a cast. A cast explicitly invokes the conversion operator from one type to another. The cast will fail if no such conversion operator is defined.

Have a read here:
MSDN: Casting and Type Conversions (C# Programming Guide)[^]
WikiPedia: Type conversion[^]
 
Share this answer
 
Comments
Clifford Nelson 13-Jul-12 18:42pm    
As usual. The MSDN articles are almost useless in helping someone understand some subject. Better to look for some 3rd party writeup.
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
C#
String.Format("{0} {1} {2}", 1, 2.3, "four");

String.Format is expecting a string and 3 objects, but it was given a string, an int, a float, and another string instead, so the last 3 arguments are cast to objects 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:
C#
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:

C#
IntComparer c = new IntComparer();
c.Compare(1,2); // not valid!
((IComparer<int>)c).Compare(1,2); // valid
 
Share this answer
 
v4

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900