I am porting a C++ program to C#. I just started to learn C#.
In C++, if I define a constructor with string parameter
class ProgramOption { public: ProgramOptions(const char* s=0); };
Then I can use string parameter in the place of ProgramOptions, such as
int myfucn(ProgramOption po);
myfunc("s=20;");
I can also use it as default argument, such as,
int myfunc(ProgramOption po=ProgramOption());
Unfortunately in C#, even I have
class ProgramOption { public ProgramOptions(const char* s=0) {...} }
I found that I can't use it as default argument,
int myfunc(ProgramOption po=new ProgramOption());
and I can't pass string literal without explicit conversion, such as
myfunc("s=20");
Is this simply impossible in C# or I can implement some method to make it happen? Thanks
You would need to define an implicit cast operator. Something like this:
class ProgramOption
{
//...
public ProgramOptions(string str = null)
{
//...
if (!string.IsNullOrWhiteSpace(str))
{
/* store or parse str */
//...
}
}
//...
public static implicit operator ProgramOptions(string str)
{
return new ProgramOptions(str);
}
}
Then would allow you to have your function like this:
int myfunc(ProgramOption po = null)
{
po = po ?? new ProgramOptions(); //default value
//...
}
And call it like this:
myfunc("some text");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With