I have to apply a method to an object in C# but I have to do it multiple times
stud1.setGrade(90); stud1.setGrade(100); stud1.setGrade(90); stud1.setGrade(50);
You get the point... The thing is I know there is a way to avoid that and just put it like this:
stud1.setGrade(90)
.setGrade(100)
.setGrade(70);
But I don't remember if that's correct in C#, I saw it in another programming language although I don't remember if that is the correct way of doing it.
Why dont you add the values you want to set into an array and then use a foreach to call .setGrade?
int[] values = int[] {90, 100, 70};
foreach(int value in values)
{
stud1.setGrade(value);
}
Just have SetGrade
return this
.
public Student SetGrade(int grade) {
this.Grade = grade;
return this;
}
This should be possible when setGrade() returns an instance of itself or when you write an extension method called setGrade() (for the class) that returns an instance of itself.
public static Student SetGrade(this Student student, int value) {
student.setGrade(value);
return student;
}
this can then be used similar to:
stud1.SetGrade(90)
.SetGrade(100)
.SetGrade(70);
Let me introduce the concept of List to you. List
is a data structure to store homogeneous data. You can use List
for your scenario.
List<int> myGrades=new List<int>();
myGrades.Add(90);
myGrades.Add(100);
myGrades.Add(70); //adding all the grades
//we will use foreach to loop through all the elements
foreach(int g in myGrades)
{
stud1.setGrade(g); //all grades are set
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With