Reputation: 2311
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
Upvotes: 4
Views: 259
Reputation: 40140
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");
Upvotes: 6
Reputation: 74018
From Does C# have default parameters?
In languages such as C++, a default value can be included as part of the method declaration:
void Process(Employee employee, bool bonus = false)
...
C# doesn't have this feature.
but also
Update:
Named and optional (default) parameters are available starting from C# 4.0.
Visual C# 2010 introduces named and optional arguments. ... Optional arguments enable you to omit arguments for some parameters.
and later
Optional Arguments
- a constant expression;
- an expression of the form new ValType(), where ValType is a value type, such as an enum or a struct;
- an expression of the form default(ValType), where ValType is a value type.
Upvotes: 1