C
C#15mo ago
Rockraizer

✅ How can I make my code reusable?

Hi! I asked a question before to calculate the average of 5 text boxes in one textbox. I wrote a code:
public class AverageViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;

public double TextBox1Value
{
get { return textBox1Value; }
set
{
textBox1Value = value;
CalculateAverage();
OnPropertyChanged();
}
}

// Define properties for TextBox2Value, TextBox3Value, TextBox4Value, TextBox5Value, and Average similarly.

private void CalculateAverage()
{
Average = (TextBox1Value + TextBox2Value + TextBox3Value + TextBox4Value + TextBox5Value) / 5.0;
}

protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class AverageViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;

public double TextBox1Value
{
get { return textBox1Value; }
set
{
textBox1Value = value;
CalculateAverage();
OnPropertyChanged();
}
}

// Define properties for TextBox2Value, TextBox3Value, TextBox4Value, TextBox5Value, and Average similarly.

private void CalculateAverage()
{
Average = (TextBox1Value + TextBox2Value + TextBox3Value + TextBox4Value + TextBox5Value) / 5.0;
}

protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
I want to use this in more situations but I don't want to define every textbox and make it really redundant.
6 Replies
Pobiega
Pobiega15mo ago
The simplest way would be to have CalculateAverage take in a list of values, instead of know all the values itself
Azrael
Azrael15mo ago
Just make a list that holds each textboxvalue and then loop through the list and divide that by 5.
Pobiega
Pobiega15mo ago
assuming you want to be be able to use this method in other forms, that might have different boxes and even other amounts of it
Rockraizer
RockraizerOP15mo ago
Thanks the idea, I will try it guys. But how will I tell him to which textboxes needed to be calculated? Mostly there are 5 or 20 textboxes will be calculated. I draw an example:
No description
Azrael
Azrael15mo ago
List<TextBox> and then grab the ones that are needed?
Rockraizer
RockraizerOP15mo ago
Ohh, okey
Want results from more Discord servers?
Add your server