c# Minimum required of optional parameters

Viewed 254

So I'm trying to get a list of relation existing between two table to validate some integration test. The database is pretty simple : Table1 <- RelationTable -> Table2 I would like to get the existing relation from a list of Table1 Ids or a list of Table2 Ids or both. If I said that my parameter are all optional, I need to verify that both aren't null or throw a exception if so. If I force both parameter and want to allow one or the other to be null, but not both, I need to create 3 methods to handle it or force the dev who will use the method to add null parameter in the call like the code below which I think it's a ugly way to do it.

Sadly this couldn't be polymorphism because the first params is the same type... But I would like to allow methodX to just be call method and allow the 3 possible methods into one without allowing method() with no params to be use.

protected async Task<List<Relation>> method1(List<string> table1Ids) => method3(table1Ids, null);
protected async Task<List<Relation>> method2(List<string> table2Ids) => method3(null, table2Ids);
protected async Task<List<Relation>> method3(List<string> table1Ids, List<string> table2Ids)
{
    if(table1Ids == null && table2Ids == null) 
        throw new ArgumentNullException();
    // code here
}

To be honest, I could choose if all null throw or 3 method or for bulletproof code choose both and it would work fine, but I'm searching alternate version where I can force a minimum of one parameter but don't said which one is required. I thought maybe attribute from the .Net Framework would do that for me, but I couldn't find something near that. I'm searching for something that could do that out of the box or a custom attribute to do that.

It would be code something like that. Without the if throw because the attribute would validate it.

[MinimumOptionalRequiredAttribute(1)]
protected async Task<List<Relation>> GetRelationFromListOfIds(List<string> table1Ids = null,
                                                              List<string> table2Ids = null) {
    // code here
}
// Example of code that could be use
{
    // Those would work
    var byTable1 = GetRelationFromListOfIds(table1Ids);
    var byTable2 = GetRelationFromListOfIds(table2Ids:table2Ids);
    var byTable1And2 = GetRelationFromListOfIds(table1Ids, table2Ids);

    // This would not be allow by the c# intellisense
    var throwException = GetRelationFromListOfIds();
}

I know I'm trying to solve everything with one method instead of going with a more "normal" way. I talk about attribute, but it not necessary an attribute. I would expect the code to not compile if you try call methodEmptyParamsNotAllow(). To be honest, I'm not even sure if that is a good idea for code readability. I'm just curious about the idea. Is something similar already exist? Is the idea good? What it would look like?

0 Answers
Related