C# - Class property as a method of variable numer of parameters

441 Views Asked by At

I have the following class

public class MyClass
{
  public int ElementId {get; set;}
  public int? LowerBoundary {get; set;}
  public int? UpperBoundary {get; set;}

  public int  SpecificMethod() {}

  public void CommonMethod()
  {
    int expectedValue = SpecificMethod();
  }
}

CommonMethod() is the same for every instance of this class, but I'd like SpecificMethod() to be different for each one. This method should always return an int, but it could take 0, 1 or 2 parameters (which are its own values for LowerBoundary and UpperBoundary properties).

Is there a way to achieve this? Since the number of parameter is variable, I understand I can't make SpecificMethod to be a Func property.

1

There are 1 best solutions below

3
AudioBubble On

Perhaps you can use params keywords:

public class MyClass
{

  public int SpecificMethod(params int[] values)
  {
    switch (values.Length)
    {
      case 0:
        ...
        break or return ...;
      case 1:
        ...
        break or return ...;
      case 2:
        ...
        break or return ...;
      default:
        ...
        break or return ...;
    }
    //return ...;
  }
}

https://learn.microsoft.com/dotnet/csharp/language-reference/keywords/params

You can also define three overloaded methods:

public class MyClass
{
  public int SpecificMethod()
  {
    return 0;
  }
  public int SpecificMethod(int value)
  {
    return 0;
  }
  public int SpecificMethod(int value1, int value2)
  {
    return 0;
  }
}

You can create as many as overloaded methods with any types you need.

https://learn.microsoft.com/dotnet/standard/design-guidelines/member-overloading

Perhaps you may set the method as private or protected if only used by the instance.