This is a really simple question concerning a method. I’m pretty new to C# and am testing lists. How do I call the method “addTwo” so that it updates every element in the “Marks” list by two? Please note that I’ve already created this method (scroll down further below the main method). I just want to know how to call it in the main method.
namespace ParallelLists
{
class Program
{
static void Main(string[] args)
{
//create an list of 4 student names
List<string> names = new List<string>(4);
names.Add("Matt");
names.Add("Mark");
names.Add("Luke");
names.Add("John");
//create a list of 4 integers representing marks
List<decimal> marks = new List<decimal>(4);
marks.Add(88m);
marks.Add(90m);
marks.Add(55m);
marks.Add(75m);
Console.WriteLine("the mark of " + names[0] + " is : " + marks[0]);
Console.ReadLine();
//Upgrade everyone by 2 marks
...
}
public List<decimal> addTwo(List<decimal> mark)
{
List<decimal> temp = mark;
for (int i = 0; i < temp.Count; i++)
{
temp[i] += 2m;
}
return temp;
}
}
}
You need to make your method static, since you are accessing on a non object. also you need to update your marks collection with the returned value. You dont actually need to return the List because list is mutable.
if you dont want to return the list, you can do the following: