Reputation: 1
I want to call the Promotion value form the class StudentApp so I could sum it up in the GetTotalScore. Here a Brief Example of the code.. Have Updated the code.
class Tester
{
static void Main(string[] args)
{
Console.WriteLine("Total score (after 10 marks promotion): " + GetTotalScore(app.Students));
}
static double GetTotalScore(List<Student> list)
{
if (list.Count == 0)
{
return 0;
}
else
{
List<Student> subList = list.GetRange(1, list.Count - 1);
double subTotal = GetTotalScore(subList);
double total = .....[0] + subTotal;
return total;
}
}
}
class StudentApp
{
public void PromoteScore(List<Student> list)
{
double Promotion = 0;
foreach (Student s in Students)
{
if (s.Score + 10 > 100)
{
Promotion = 100;
}
else
{
Promotion = s.Score + 10;
}
}
}
}
Any Help is Appreciated!
Upvotes: 0
Views: 69
Reputation: 26989
Option 1
Make it a property like this:
class StudentApp
{
public double Promotion { get; private set; }
public void PromoteScore(List<Student> list)
{
foreach (Student s in Students)
{
if (s.Score + 10 > 100)
{
Promotion = 100;
}
else
{
Promotion = s.Score + 10;
}
}
}
}
Then you can access it like this;
var app = new StudentApp();
app.PromoteScore(//students...);
double promotion = app.Promotion;
Option 2
Or you can just return the promotion from the method like this:
class StudentApp
{
public double PromoteScore(List<Student> list)
{
double promotion = 0;
foreach (Student s in Students)
{
if (s.Score + 10 > 100)
{
Promotion = 100;
}
else
{
Promotion = s.Score + 10;
}
}
return promotion;
}
}
And you would use it like this;
var app = new StudentApp();
double promotion = app.PromoteScore(//students...);
Upvotes: 1
Reputation: 3048
As UnholySheep said in the comments, the issue here lies in that your variable is a local variable whose scope is only within that method. That is, it exists only while the scope of the program is in that method, once you leave the scope you have no access to that method. Instead, make it into a public class level variable.
class StudentApp {
public double Promotion {get; set;}
//do you coding here
}
then if you want to access it, you can simply say StudentApp.Promotion
. If you are wondering about what does {get; set;} mean, this is a way in C# to quickly make a simple getter and setter instead of having to write out a method to get the value, and to set it as you may do in Java.
Upvotes: 0