Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid repeating "object.method()" in C#?

Tags:

methods

c#

object

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.

like image 750
Johnny Beltran Avatar asked May 11 '15 04:05

Johnny Beltran


4 Answers

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);
}
like image 55
Ganesh R. Avatar answered Nov 05 '22 18:11

Ganesh R.


Just have SetGrade return this.

public Student SetGrade(int grade) {
    this.Grade = grade;
    return this;
}
like image 35
John Saunders Avatar answered Nov 05 '22 16:11

John Saunders


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);
like image 3
Nathan White Avatar answered Nov 05 '22 16:11

Nathan White


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
}
like image 3
Abhishek Avatar answered Nov 05 '22 16:11

Abhishek