简体   繁体   中英

Implicit type conversion in C#

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");

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.

Named and Optional Arguments

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM