Sunday 15 September 2013

C# user defined struct conversion as function's default parameter

C# user defined struct conversion as function's default parameter

public struct MQL4Int
{
public int csInt;
public MQL4Int(int i)
{
csInt = i;
}
public static implicit operator MQL4Int(int value)
{
return new MQL4Int(value);
}
}
int MyFunc(MyInt i = 0)
{
return -1;
}
I want to implement a wrapper struct MyInt (simplified here) to accept int
as default value (I know this is weird and unnatural, I just need it to
comply other language format), but I meet error when I code like above,
the error is at 'int MyFunc(MyInt i = 0)' where VS2012 said
"a value of type 'int' cannot be used as a default parameter because there
are no standard conversions to Type MyInt"
As I know, int and double also defined as struct in C#. So I have tried
follows:
int MyFunc(double i = (int)0)
{
return -1;
}
it passed! Therefore I think type conversion is allowed in default parameter.
So my questions are:
Why can not use implicit type conversion for MyInt as default para?
What does the standard conversions mean in VS error message, is it diff
from implicit conversion defined in MyInt?
Thanks for all

No comments:

Post a Comment