0

What is the best way to achieve this: I have a class with 2 method overloads which I create n object from. If I define b it will used and if not the default. Where/How do I use this default without changing it permanently in the object. What I did is the following but there must be a simpler way.

.
.
.
private int b = 100;
private readonly int defualt_b = 100;

public void Press(int a)
{   
...do something...
   Send(a, b);
}

public void Press(int a int new_b)
{    
...do something...
    b = new_b; //set b to be used
     Press(a);
    b = default_b; //reset back to its default value
}
dandan
  • 509
  • 3
  • 8
  • 21
  • Does this answer your question? [method overloading vs optional parameter in C# 4.0](https://stackoverflow.com/questions/3316402/method-overloading-vs-optional-parameter-in-c-sharp-4-0) – Pavel Anikhouski May 30 '20 at 20:20
  • I'd probably clean up use of the `b` field - push it down to an "implementation function" (possibly the new method with a second parameter) that accepts the value _without_ using transient state. With this done, there is little benefit here to using optional parameters (which I avoid using or recommending in most cases unless such is a core design-choice with maximized value). – user2864740 May 30 '20 at 20:31

2 Answers2

2

The context is not completely clear so I am not sure if I understood the problem correctly. Specifically is the private int b used anywhere else and thus needs to be set to some particular value ? Or is it just a helper field ? If the latter, then just change the dependency between the two overloads :

private const int DefualtB = 100;

public void Press(int a)
{   
   Press(a, DefualtB);
}

public void Press(int a int new_b)
{    
   ...do something...
   Send(a, new_b);
}

EDIT: Also this assumes that those "..do something.." blocks in the original code were meant to be the same and done once. If not , then this will be somewhat more complicated.

mcc
  • 135
  • 7
0

Add an optional parameter

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/named-and-optional-arguments

public void Press(int a , int new_b = 100)
{    
}
G.Mich
  • 1,607
  • 2
  • 24
  • 42