user8405
user8405

Reputation: 27

Creating a class instance in main method in C#, errors CS0120 and warning CS0169

I am trying to create a class instance in main method with constructor (I removed static in the methods above), but can't seem to figure out how to activate it with the instance. Please help thank you.

This is the code I am using and I screenshot-ed the errors I get.

using System;

namespace CalculatorTest
{
    class Calculator
    {
        public int operand1;
        public int operand2;

        public Calculator(int operand1, int operand2, int s, int n)
        {
            this.operand1 = operand1;
            this.operand2 = operand2;
        }

        public string WriteText(string s)
        {
            return s;
        }
        public int WriteNumber(int n)
        {
            return n;            
        }
    }
    class Program    
    {
        private static int operand1;
        private static int operand2;

        public static void Main(string[] args)
        {                
            string s = Calculator.WriteText("Hello world!");
            Console.WriteLine(s);

            int n = Calculator.WriteNumber(53 + 28);
            Console.WriteLine(n);

            Console.Read();
        }
    }
}

enter image description here

Upvotes: 0

Views: 203

Answers (1)

Pavel Anikhouski
Pavel Anikhouski

Reputation: 23228

You have to create a Calculator instance (and pass operand values to constructor) before accessing its non-static methods. Also make sense to remove s and n parameters from constructor, since you've passed them to methods

class Calculator
{
    private int operand1;
    private int operand2;

    public Calculator(int operand1, int operand2)
    {
        this.operand1 = operand1;
        this.operand2 = operand2;
    }

    public string WriteText(string s)
    {
        return s;
    }
    public int WriteNumber(int n)
    {
        return n;            
    }
}
var calculator = new Calculator(operand1, operand2);
string s = calculator .WriteText("Hello world!");
Console.WriteLine(s);

int n = calculator .WriteNumber(53 + 28);
Console.WriteLine(n);

Upvotes: 1

Related Questions