Force444
Force444

Reputation: 3381

Is it possible in C# to require exactly one of two parameters, to be passed in to the method?

Consider,

public void Test(Type1 param1, Type2 param2)
{
   //...
}

I'm wondering if it's possible in C# to require that when Test is invoked that it must contain exactly one parameter. I.e. Test(param1) OR Test(param2) (where param1 and param2 are of type Type1 and Type2 respectively. it shouldn't be possible to invoke Test(param1, param2).

My purpose is to enforce restriction, so using optional parameters hasn't worked for me.

As the question is not clear for everyone consider below example:

public void Test(int age, DateTime dob)
{
   //
}

I only need ONE of the parameters to determine the age. So is it possible to restrict the invoking of the method Test such that it can only be invoked with EXACTLY one parameter, i.e. either age or dob, but it shouldn't be invoked with both.

Upvotes: 3

Views: 3936

Answers (1)

Eugene Podskal
Eugene Podskal

Reputation: 10401

I recommend you to use overloaded methods:

public void Test(Type1 param1)
{
   this.Test(param1, null);
}

public void Test(Type2 param2)
{
   this.Test(null, param2);
}


private void Test(Type1 param1, Type2 param2)
{
   //...
}

If there is no problem with type inference you will have no problems.

EDIT

In your case you will have some problems - your params are structures(they can't be null). In such a case you will have to use this.Test(default(Type1), param2); Which will bring even more problems inside the method - how can we differentiate whether the value of 0(default(int)) was given into the method or it was given as default and the dateOfBirth should be used instead.

I don't think that optional params will help, because only the right param will be optional and the problem of differentiation between automatic and user-given values is still unsolved, while code contracts may be useful:

public void Test(Type1 param1, Type2 param2)
{
    Contracts.Requires((param1 == null && param2 != null) || (param1 != null && param2 == null),       "Only one parameter is needed");
    // ...
}

But I'm not sure why you will really need such a solution (method with two intermittently optional params). You will have to deal with the fact that one of the params is null(or default struct) - that's at best one more branch to increase the complexity of Test(Type1 param1, Type2 param2). I'd recommend you to use two separate one-param methods:

public void CheckSomeAgeRelatedInfo(int age)
{
   //
}


public void CheckSomeAgeRelatedInfo(DateTime dateOfBirth)
{
   //
}

Upvotes: 12

Related Questions