This is my object
public class Totals {
public int Total1 { get; set; }
public int Total2 { get; set; }
public int Total3 { get; set; }
public int Total4 { get; set; }
}
Incrementing the values of Total1 and Total2 using calculateTotals method
private Totals calculateTotals(Totals t) {
if (//condition) {
t.Total1 += 1;
} else {
t.Total2 += 1;
}
return t;
}
**Incrementing value of Total3 and Total4 of the same object with same conditions at a different location using different method calculateOtherTotals, at this point I only need to update Total3 and Total4 **
private Totals calculateOtherTotals(Totals t) {
if (//condition) {
t.Total3 += 1;
} else {
t.Total4 += 1;
}
return t;
}
I am new to c# , I need to increment the values Total1,Total2 and Total3,Total4 separately and the code which I have is working fine
Is there a way to improve my code?, how can I avoid creating two different methods which pretty much does the same logic on different properties? is there a way to create only 1 method to achieve my functionality?
3
Answers
You could do it this way, but essentially the amount of code doesn’t change.
This adds a judgment:
Call it like this:
Then it depends on how you want your method (function) to be. (E.g., how you define what your function will do and how your class and properties are characteristic—which, currently, many who want to help you still wonder about.)
Let me give another clear example.
Assume that you answer your additional requirement are:
calculateOtherTotals
being private, because of some unexplained reason such as “I don’t like others knowing it exists”.Then
Reflection is one way, though its slow and not a Domain Specific Language:
Or perhaps you want to abstract the properties you’re incrementing:
I’d personally have a
List<int>
orint[3]
and make the condition calculate the index 0-3:This way its extensible for more totals and you get inbuilt functions like LINQ, eg
Totals.Sum()
.