Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Passing a class or something similar as a parameter with default

I am trying to find a quick fix for an issue we have. I need to pass multiple optional parameters to multiple static methods and i also need to pass a couple new params Type[] parameters to add.

Obviously you can’t have i.e. params string[] param1 with other optional parameters.

Currently the best option i thought about was to create a custom class with a simple params in the constructor.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The problem is that i can’t find a way to setup a default value to make the parameter optional as it ask for a constant value and i can’t have that with a class. I also cannot make the parameter non optional as it shows error on every 70,000+ references.

So i would like to find a way to do the following somehow

public class CustomClass
{ 
    public CustomClass(params string[] stringParams)
    {
            
    }
}


public static object GenerateData(Manager manager, 
                                  string param1, 
                                  int param2, 
                                  string optionalParam1 = "incomplete", 
                                  CustomClass paramsClass = new CustomClass("val1","val2"))
{
    return "";
}

>Solution :

You could do something like this:

public static object GenerateData(Manager manager,
                                  string param1,
                                  int param2,
                                  string optionalParam1 = "incomplete",
                                  CustomClass paramsClass = null)
{
    paramsClass = paramsClass ?? new CustomClass("val1", "val2");
    return "";
}

Keep in mind, if this method resides in a library and those 70,000 calls are in something that references your library (rather than being in the same assembly, which you will recompile after this change), this is a breaking change. Just because you add an optional parameter doesn’t mean existing code will work if you don’t recompile that code.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading