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?
Type casting isn’t boxing or unboxing, but it may cause either.
As an
intisn’t aFirstClass, that is, int doesn’t inherit or extendFirstClass, hence you can’t cast it to be of typeFirstClass.Typecasting causes conversion, only if it is possible to do so.
So you can go from an int to a double and vice versa, with possible side effects. But you can’t go from an
inttoFirstClass.Boxing, wraps a value or reference type in wrapper object. At least that’s how I think of it. Not sure how the internals work, but my guess is the assignment operator “=” or casting implicitly returns the wrapped value when unboxing, and the wrapper object when boxing.