I'm currently trying to get my head around casting and boxing. As i understand it currently:
- Boxing - Value Type to Reference Type (ie int to object)
- Unboxing - Reference Type to Value Type (ie object to int)
- Type Casting - Seems to me at the moment to be similar to boxing but allows you to assign what type of object you would like the Reference Type to be of. (ie int to customObjectType)
The example im working with at the moment to try and get my around it. Say I have 2 classes, a method in one class calls the constructor of the other.
//1st class
public class FirstClass
{
//code for fields,constructor & other methods
public void CallOtherClass(int firstClassID)
{
int x = firstClassID;
SecondClass test = new SecondClass(x);
}
}
//2nd class
public class SecondClass
{
public SecondClass(FirstClass firstClass)
{
//set some fields
}
}
Ok, so in the above scenario we would have a problem as the method CallOtherClass attempts to set the constructor of SecondClass, however the constructor of SecondClass takes a parameter of type FirstClass and all we can provide is an int.
So as i understand it this would be a good time to use type casting? Something like below.
//1st class
public class FirstClass
{
//code for fields,constructor & other methods
public void CallOtherClass(int firstClassID)
{
int x = firstClassID;
FirstClass a;
a = (FirstClass)x;
SecondClass test = new SecondClass(a);
}
}
//2nd class
public class SecondClass
{
public SecondClass(FirstClass firstClass)
{
//set some fields
}
}
In my head this seems to me to change the type of x to a reference type of FirstClass. Obviously my understanding is way off some where along the lines as it produces an error
"Cannot convert type 'int' to 'Namespace.FirstClass"
Any thoughts?