Possible Duplicate:
C# Implicit/Explicit Type Conversion
I have an int that I am attempting to box, so as to use it in a constructor which takes as a parameter object of CustomType.
An example of what I mean.
int x = 5;
object a = x;
CustomType test = new CustomType(a)
//constructor in question
public CustomType(CustomType a)
{
//set some variables etc
}
Howver I get the following error
The best overloaded method match for X has some invalid arguments.
So obviously I’m way off the mark. Where am I going wrong? Is boxing the right solution or should i be looking at type casting?
That constructor takes a
CustomTypetype as a parameter; you’re passing it anint. Anintis not aCustomType, and the C# language knows of no implicit conversions frominttoCustomType. That’s why you’re getting an error.Casting the
intto anobjectdoesn’t change the fact that it’s still not aCustomType.Looking at that particular constructor, it’s a copy constructor. It takes a type of itself as a parameter. There is (one would hope) another constructor that takes another parameter, whether that’s an int, or some other type that you haven’t mentioned, or possibly no parameters and you need to just set a property after creating a default object.
As for actual solutions, there are many. Here are a few:
CustomTypethat accepts anint.intas a parameter and returns aCustomObject; this would be a “conversion” function that you could use.CustomTypeand set a property with your integer (may or may not be applicable, depending on whatCustomTypedoes.Boxing doesn’t seem to be related to the issue at hand. It’s not something that you should use to pass an integer to a custom type. If you would like to know more about what boxing is, how it works, or when it’s useful then consider asking a question that addresses those points because this particular problem would be harmed by using boxing as a solution, not helped.