-1

I new to Visual C# and just wanted to create a tiny CLI-based application. With the written codes below, I am receiving this error: "Object reference not set to an instance of an object.". Obviously, since I'm a noob, I have no idea how fix the problem.

Here's the code I have in Program.cs:

class Program
{
    static void Main(string[] args)
    {
        GetAverage(args);
    }

    static void GetAverage(string[] s)
    {
        var ave = new Average();

        ave.arg = s;
        ave.FindAverage();
        ave.DisplayResult();
    }
}

Here's the code I have in the Average.cs:

public class Average
{
    public Average()
    {
        Console.Write("\n" + "Given numbers: ");

        foreach (string s in this.arg)
        {
            Console.Write(this.arg + " ");

            num += Double.Parse(s);
        }
    }

    public double num = 0;
    public string[] arg;
    public double result;

    public void FindAverage()
    {
        this.result = this.num / this.arg.Length;
    }

    public void DisplayResult()
    {
        Console.WriteLine("\n" + "Average: " + this.result);
    }
}

What I wanna do is to access the arguments from Main method of the Program class so that I can work with it from the Average class.

Please help me with this one. Thanks!

Calum
  • 1,889
  • 2
  • 18
  • 36
Mores Jr
  • 3
  • 2
  • 7
    `var ave = new Average();` causes your constructor to execute. At this point, `args` is not set, so it will give you an error at `foreach (string s in this.arg)`. Make your constructor take `string[] args` and set `this.arg = args` at the start of your constructor. – Rob Sep 24 '15 at 11:27

1 Answers1

4

The field public string[] arg; is used in your constructor, but it is set after the constructor has run. Try something like this instead:

public Average(string[] arg)
{
    this.arg = arg

    // ..
    // existing code
}
user1793963
  • 1,295
  • 2
  • 12
  • 24
  • Thank you for the speedy response. Your answer, the code revision, totally solved the error. But now, a new error popped out. "Input string was not in a correct format." Maybe I'm just inputting wrong data type? I'm parsing the args into Double so that I can compute it. – Mores Jr Sep 24 '15 at 11:47
  • Try using '.' instead of ',' for decimals (or the other way around). Also check if the array contains any empty strings. – user1793963 Sep 24 '15 at 12:07