-2

I've just recently started my intermediate course in C# programming and I'm learning how to create multiple classes and creating methods to use in my program.

It's a very new topic to me so I apologize if it's something very obvious or stupid. I am getting below message in all of my methods:

Cannot access static method in non-static context

Code in method class:

public static int Add(params int[] numbers) {
        var sum = 0;

        foreach (var n in numbers) {
            sum += n;
        }

        return sum;
    }

    public static int Subtract(params int[] numbers) {
        var sum = 0;

        foreach (var n in numbers) {
            sum -= n;
        }

        return sum;
    }

    public static int Multiply(params int[] numbers) {
        var sum = 0;

        foreach (var n in numbers) {
            sum *= n;
        }

        return sum;
    }

    public static int Divide(params int[] numbers) {
        var sum = 0;

        foreach (var n in numbers) {
            sum /= n;
        }

        return sum;
    }

    public static string[] CheckingOfSomeSort(string userInput, int value, bool isAddition, bool isSubtraction, bool isDivision, bool isMultiplication) {
        if (userInput.Contains("+")) {
            var addition = userInput.Split('+');
            value = 1;
            isAddition = true;
            return addition;
        } else if (userInput.Contains("-")) {
            var subtraction = userInput.Split('-');
            value = 2;
            isSubtraction = true;
            return subtraction;
        } else if (userInput.Contains("*")) {
            var multiplication = userInput.Split('*');
            value = 3;
            isMultiplication = true;
            return multiplication;
        } else if (userInput.Contains("/")) {
            var division = userInput.Split('/');
            value = 4;
            isDivision = true;
            return division;
        }

        return null;
    }

I am attempting to create a calculator (which I have already done, however I'm trying to use methods now)

5
  • which line throws this error Commented May 29, 2018 at 4:07
  • 2
    there is no calling of these method in code you provided, would like to add that part too ? Commented May 29, 2018 at 4:09
  • @Amit The calling would be in my main method. 'var calc = new CalculatorMethods(); calc.Add();' When adding numbers, it does not work, and when I hover over the red line the message I get is "Cannot access static method in non-static context" Commented May 29, 2018 at 4:14
  • @MrSanfrinsisco these methods are static. (and the way they are used they should be static too). But static methods cannot be accessed with object of Class but with directly Type of the class. here I m guessing CalculatorMethods is class in which methods are and you will try to do something like calc.Add() .. which will not be possible . Instead do CalculatorMethods.Add() Commented May 29, 2018 at 4:18
  • Possible duplicate of C# Compiler : cannot access static method in a non-static context Commented May 29, 2018 at 4:49

3 Answers 3

5

As per your comment I got to know that you are creating an object of CalculatorMethods and you are trying to call methods of that class which are static using this object.

My Comment on question:

these methods are static. (and the way they are used they should be static too). But static methods cannot be accessed with object of Class but with directly Type of the class. here I m guessing CalculatorMethods is class in which methods are and you will try to do something like calc.Add() .. which will not be possible . Instead do CalculatorMethods.Add()

Instead you can try it by calling with Type directly like belwo,

    void MethodOfCalling()
    {
        int sum = CalculatorMethods.Add(new int[2] { 1, 2 });
    }

you can see, I have used CalculatorMethods (a class name - more properly saying Type of the class) to call method not object of the class.

Sign up to request clarification or add additional context in comments.

6 Comments

So I cannot create an object of that class and use that to call the methods? I would have to use the class name itself, just as a side note, is creating an object for using constructors then?
you can create object of that class, it will call constructor too. and you can use that object to call non static method too but point is that only. static members and methods cannot be called with object.
@MrSanfrinsisco static methods are methods on the Type (the class name that you're referring to is the Type you're defining). So, yes. you would use the Type Method. You use a constructor to initialize an instance of a Type.
It seems I've been programming this whole time with the wrong knowledge of the static modifier. In this situation would making my methods static or not making them static make any difference?
having said that, you can create Extension Method (Static Methods) that apply to instances of the Type.
|
3

@MrSanfrinsisco, Welcome to C# programming. As you ask its very easy to call static methods. to make a call follow the below steps

1) create 1 class file . Lets say its Calculations.cs [put your code inside this class] final layopout of your class will be..

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication3.Models
{
    public class Calculations
    {
        public static int Add(params int[] numbers)
        {
            var sum = 0;

            foreach (var n in numbers)
            {
                sum += n;
            }

            return sum;
        }

        public static int Subtract(params int[] numbers)
        {
            var sum = 0;

            foreach (var n in numbers)
            {
                sum -= n;
            }

            return sum;
        }

        public static int Multiply(params int[] numbers)
        {
            var sum = 0;

            foreach (var n in numbers)
            {
                sum *= n;
            }

            return sum;
        }

        public static int Divide(params int[] numbers)
        {
            var sum = 0;

            foreach (var n in numbers)
            {
                sum /= n;
            }

            return sum;
        }

        public static string[] CheckingOfSomeSort(string userInput, int value, bool isAddition, bool isSubtraction, bool isDivision, bool isMultiplication)
        {
            if (userInput.Contains("+"))
            {
                var addition = userInput.Split('+');
                value = 1;
                isAddition = true;
                return addition;
            }
            else if (userInput.Contains("-"))
            {
                var subtraction = userInput.Split('-');
                value = 2;
                isSubtraction = true;
                return subtraction;
            }
            else if (userInput.Contains("*"))
            {
                var multiplication = userInput.Split('*');
                value = 3;
                isMultiplication = true;
                return multiplication;
            }
            else if (userInput.Contains("/"))
            {
                var division = userInput.Split('/');
                value = 4;
                isDivision = true;
                return division;
            }

            return null;
        }
    }
}

2) then go to the page inside which you want to access that method and simply write. Here for example if you want to use it on default.aspx then use below method. [Note: you must give name space of your class here then only you are able access this class in my example it is, using WebApplication3.Models;]

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebApplication3.Models;

namespace WebApplication3
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            int resultAdd= Calculations.Add(new int[3] { 1, 2, 3 });
            int resultSubstract= Calculations.Subtract(new int[3] { 1, 2, 3 });
            int resultDivide= Calculations.Divide(new int[3] { 1, 2, 3 });
            int resultMultiply=Calculations.Multiply(new int[3] { 1, 2, 3 });
        }

    }
}

this is the basic notes to call such kind of methods.

Let me know still you need any help. :)

1 Comment

hmm.. can you update your example of usage to assign the return values
0

To call the static method you need to refer to it from the class it's defined in, not an instance of that class. eg :

Calculator.Divide(); // works 


Calculator obj = new Calculator(); 
obj.Divide(); // Not works

NOTE : Divide() is a static method

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.