I’m a beginner in C# and I’m working on this program consisting of 4 methods including Main(). The GetValues() allows user to input an array, the FindAverage() calculates the average of the array and now I want to create a third method ‘Show()’ that is supposed to display the results.
I got this working when I display the average inside Main() but when i do it inside Show(), nothing happens. While testing it, I made Show() display a simple text line “message” but when i run it. Seems like the program skips Show() and goes straight to Main(). Can any of you explain to me what’s going on and what do i have to do so Show() displays it’s contents?
Thank you guys!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace testscores
{
class Program
{
private static int GetValues()
{
string inValue;
int[] score = new int[5];
int total = 0;
for (int i = 0; i < score.Length; i++)
{
Console.Write("Enter Value {0}: ", i + 1);
inValue = Console.ReadLine();
score[i] = Convert.ToInt32(inValue);
}
for (int i = 0; i < score.Length; i++)
{
total += score[i];
}
return total;
}
//FIND AVERAGE
private static double FindAverage()
{
double total = GetValues();
double average = total/5.0;
return average ;
}
//Show
static void Show()
{
Console.WriteLine("message");
return;
}
static void Main()
{
double avg = FindAverage();
Console.WriteLine("The Average is :" + avg);
Console.ReadKey();
}
}
}
Programs don’t run all the code you type. They execute each statement within
Main, and each statement within each method that gets called byMain.In your
Mainmethod, you call these other parts of your program:In your
FindAveragemethod, you call these other parts:In your
GetValuesmethod, you don’t call any other parts of your program.Nowhere in this chain do you specifically call
Show, so it never gets called. It just sits inside your .exe file, doing nothing.This is called dead code. It isn’t a big deal, but it sounds like it isn’t what you want.
To fix this, add this line somewhere in your code, wherever in your program’s flow you’d like it to run: