Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicit type conversion in C#

Tags:

c++

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

like image 544
cuteCAT Avatar asked Mar 21 '23 15:03

cuteCAT


1 Answers

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");
like image 74
Theraot Avatar answered Mar 23 '23 05:03

Theraot