Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I have conditional out parameters

Tags:

c#

The method DoSomething() does Create an Instance of MyClass but not everyone wants to know the MyClass-Object sometimes it also fits if you simply know if the action was successful.

This doesn't compile

public bool DoSomething(out Myclass myclass = null)
{
    // Do something
}

A ref or out parameter cannot have a default value

Sure I could simply remove the out-Keyword but then I needed to assign any variable first, which is not my intention.

This could be a workaround, but i want bool to be the return type

public Myclass DoSomething() //returns null if not successful
{
    // Do something
}

Does anyone know a nice Workaround for that?

like image 273
LuckyLikey Avatar asked Dec 05 '22 22:12

LuckyLikey


1 Answers

Just by overloading:

public bool DoSomething()
{
    myClass i;
    return DoSomething(out i);
}

public bool DoSomething(out myClass myclass)
{
    myclass = whatever;
    return true;
}

And then call DoSomething()

like image 53
Thomas Ayoub Avatar answered Dec 24 '22 15:12

Thomas Ayoub