Can't call function in C# [duplicate] - c#

This question already has answers here:
CS0120: An object reference is required for the nonstatic field, method, or property 'foo'
(9 answers)
Closed 10 months ago.
Im trying to call this calculator function:
public static void Main(string[] args) {
int answer = calculate(int a, int b);
Console.WriteLine(answer);
}
public int calculate(int a, int b) {
return a + b;
}
but I keep getting an error about making a non-static reference

The reason you can't call your function is because you can't call a non static function from a static function, try adding the static keyword to your calculate function header

instance member function cannot be called from static function, so you need to make other function static aswell
public static void Main(string[] args) {
int answer = calculate(int a, int b);
Console.WriteLine(answer);
}
public static int calculate(int a, int b) {
return a + b;
}
to call it without making it static you need to create object of the class for example
class Example{
public static void Main(string[] args) {
Example example = new Example();
int answer = example.calculate(int a, int b);
Console.WriteLine(answer);
}
public int calculate(int a, int b) {
return a + b;
}
}

The static keyword means the method does not require an instance of the class in order to be invoked. For example:
MyClass.MyMethod(); // can be called without using the new keyword
Conversely, a non-static method does require an instance of the class in order to be invoked. For example:
var myInstance = new MyClass(); // create instance of class
myInstance.MyMethod(); // then call non-static method
If you think about it for a moment, you can see why a static method cannot call a non-static method. Static methods may be used when the method does not need access to instance level variables or methods. If your static method does need access to the non-static method you have 2 options:
remove the static keyword (EDIT: woops you are calling directly from main so this isn't possible in this case since main must be static. It usually is though)
make the other method static

Related

why can't I use modifier when I create method in Main method?

I am trying to make simple add method. what I've figured out so far is that I have to declare static when I create method outside of main function and I can't use modifier in Main method when I create method. but I need more precise insight why?
My code is below.
1.Use Static
static void Main(string[] args)
{
int a = 100;
int b = 200;
int add = Add(a, b);
int sub = Subtract(a, b);
System.Console.WriteLine($"This is Practice3: {add}");
System.Console.WriteLine($"This is Practice3: {sub}");
}
static public int Add(int k, int q)
{
return k + q;
}
static public int Subtract(int y, int z)
{
return y - z;
}
in this code, the reason using static for Add, Subtract method is to use them in Main method without instantiating them? Am I right? that means each method are Object type?
2.
static void Main(string[] args)
{
int a = 100;
int b = 200;
int add = Add(a, b);
int sub = Subtract(a, b);
int Add(int k, int q)
{
return k + q;
}
int Subtract(int y, int z)
{
return y + z;
}
System.Console.WriteLine($"This is Practice3: {add}");
System.Console.WriteLine($"This is Practice3: {sub}");
}
However, in 2nd code, V.S doesn't allow me to use modifier(like public, private...). It just does allow me to use return type of method.
I don't understand why.
does anybody give me some clues? Thank you in advance!!
Couple of points here -
The reason using static for Add, Subtract method is to use them in
Main method without instantiating them? Am I right? that means each
method are Object type?
Yes. you can access them without instantiating the Program object, That is the main feature of the static methods in C#. Suppose if you want to access these methods outside of Program Class then you could use them something like below -
class TestClass
{
public void printAdd()
{
int addResult = Program.Add(3, 3);
Console.WriteLine(addResult);
Console.Read();
}
}
V.S doesn't allow me to use modifier(like public, private...). It just
does allow me to use return type of method. I don't understand why.
In C# -
Access modifiers are keywords used to specify the declared
accessibility of a member or a type.
So with the very definition of the access modifiers it should be applied to members. In case of your code Main Method is a member of a class(Main). Similar can be applied to add and subtract methods in the 1st code snippet and you can apply modifiers there.
So you cannot apply the access modifiers to add and subtracts methods in 2nd code snippet. They are local variables declared inside a method and not members of a type Program. You may have to see the below answer for more information on member variables and method variables -
Difference between Class variable, Member variable, and Local variable, Global Variable
And below link for access rules on access modifiers for different type members -
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/accessibility-levels
Visual Studio doesn't allow me to use a modifier(like public, private...). It just does allow me to use the return type of method. I don't understand why.
It's because you are trying to create methods inside the main function.
You can create methods with modifiers only from the outside of the function. You do not need to add a modifier because its already in the function.
Compiler counts that function as a local function.

Unity3d, C# pass function as parameter

I have ScriptA with a lot of void functions:
void methodOne() {
some code
}
void methodTwo(int a, int b) {
}
I want to pass to static method of another script. Lets say it scriptB:
ScriptB.staticMethod(methodOne, some, other, primitive, parameters);
ScriptB.staticMethod(methodTwo(a, b), some, other, parameters);
The main Idea of my scripts is that ScriptB will get datas from server and call methods that got from ScriptA to make changes in my game depending on data.
I am not sure what you are trying to achieve here.
But to answer your question, you can pass methods as parameters using delegates. Here is an example:
public class ScriptA
{
public delegate void MethodOneDelegate(int a, int b);
public void MethodOne(int a, int b)
{
Console.WriteLine(a + b);
}
}
public static class ScriptB
{
public static void StaticMethod(ScriptA.MethodOneDelegate function, int a, int b)
{
function(a, b);
}
}
public static void Main()
{
ScriptA scriptA = new ScriptA();
ScriptB.StaticMethod(scriptA.MethodOne, 1, 2);
}
There is alternative solutions, you can take a look at System.Func and System.Action.
Do you need to start the methods when you put them as parameters? Or do you need the values from those methods?
Either way, you could do two things, either try this or just pass the name of the method as string and in your method check which name has been entered and start that method in your method.

How do I access an instance of a class from a static method?

How can I access a current instance of a class from a static method? The static method is necessary. I just want to get the count of the current child forms of the Parent form. My code is below but it says 'Application' does not exist in the current context
private static ReturnOpenWindowCount()
{
Form f = (Form)Application.OpenForms["Form1"]
if(f.Children.Length > 0){//Do Something;}
}
You can't, a static method has no 'current instance'. You could invoke the static method while there are 100 instances around, or 0, and it would work in both cases. It has no relationship to any instances unless you explicitly make one, for example by keeping a private static array of instantiated forms. That would quite likely be bad style and an XY solution though in relationship to forms.
Youc could pass the Application instance in parameters to this method
pass the instance as a parameter. thats as close as you can get..
void Main()
{
Foo foo = new Foo();
Foo.ThisFoo(foo);
Console.WriteLine(foo);
Console.ReadLine();
}
// Define other methods and classes here
class Foo
{
int x = 0;
public static void ThisFoo(Foo foo)
{
foo.x = 1;
}
public override string ToString()
{
return "" + x;
}
}

Why Static Methods are allowed only to call static methods not non static methods [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Why can I only access static members from a static function?
While I was trying to call a normal method from inside a static method I got the error:
An object reference is required for the non-static field, method, or property
So this means I need to create the object of the Class and then call the nonstatic method. If I want to call the method directly then I have to declare that method as Static.
But , in this scenario , the calling method and called method belong to same class. So Why do I need to create an object while calling from a Static Method , while I can call a non-static method from non static method.
Ex:
class Program
{
//public void outTestMethod(int x,out int y)
//{
// y = x;
//}
static void Main(string[] args)
{
int a = 10;
int b = 100;
outTestMethod(a,out b);
}
private void outTestMethod(int x, out int y)
{
y = x;
}
}
Error:An object reference is required for the non-static field, method, or property
Static methods can call instance methods - but you need to have an instance on which to call them. It doesn't matter where that instance comes from particularly, so for example:
int a = 10;
int b = 100;
Program program = new Program();
program.outTestMethod(a,out b);
Instance methods are associated with a particular instance of the type, whereas static methods are associated with the overall type instead - and the same is true for other kinds of members. So to call an instance method, you need to know which instance you're interested in. For example, it would be meaningless to have:
string name = Person.Name;
because you need to know which person you're talking about:
Person person = FetchPersonFromSomewhere();
string name = person.Name;
... that makes much more sense.
Typically instance methods use or modify the state of the instance.
Consider it this way.
A static method is the button outside a bank of elevators. Anyone can see it and push it, and make something happen (i.e. one of the elevators will arrive at that floor).
The non-static methods are the buttons inside a specific elevator. They manipulate THAT elevator (and none of the others).
A non-static method is also called an instance method. This means there (usually) is a chunk of data, specific to the instance (object) that the method operates on.
You can't call a non static or instance method from a static method because it wouldn't know which instance or object to operate on.
Because there is no instance to call the method from. YOu should create possibly another class and test on that:
class Program
{
static void Main(string[] args)
{
int a = 10;
int b = 100;
Test testclass = new Test();
testclass.outTestMethod(a,out b);
}
}
class Test
{
public void outTestMethod(int x, out int y)
{
y = x;
}
}
do you understand the difference between instance method and static method?
an instance method has access to the this object even if it's not passed in as parameter, in fact it's like if it was an invisible parameter of the same type of the class passed for you by the framework.
a static method does not have that this object and cannot call instance methods because it does not have anything to pass for that this in the invisible way...
sounds like a joke but this is the way I see it :)

Delegates Program

I made a very simple program of Delegates. I have no idea why is it showing error, even though I compared it with the one given in MSDN library, its same like the one in MSDN, still not getting compiled..the error says- "The name 'Add' does not exist in the current context "and same for the other method.. Subtract.
Please help me find what is the problem..
namespace DelegatePrac
{
public delegate void One(int a, int b);
public class Some
{
static void Add(int a, int b)
{
int c = a + b; Console.WriteLine("{0}",c);
}
static void Subtract(int a, int b)
{ int c = a - b; Console.WriteLine("{0}",c);
}
}
class Program
{
static void Main(string[] args)
{
One o1,o2;
o1 = Add;//gives error here
o2 = Subtract;//and here!!
o1(33,44);
o2(45, 15);
Console.ReadLine();
}
}
}
I was following this link- http://msdn.microsoft.com/en-us/library/ms173175.aspx
Thanks
You should see a compiler message:
The name 'Add' does not exist in the current context
which tells you that it has no clue which Add method you are talking about; Add is a static method in Some - so you need:
o1 = Some.Add;
o2 = Some.Subtract;
static methods aren't globally available; you can access static methods from the current type (and from base-types) via just their name, but if it is an unrelated type you need to qualify it with the declaring-type.
At this point it will give you a compiler error:
'DelegatePrac.Some.Add(int, int)' is inaccessible due to its protection level
which hints that it is a private method; so add public (or internal) to them:
public static void Add(int a, int b) {...}
Have you tried exchanging those two lines with errors with this?
o1 = Some.Add;
o2 = Some.Subtract;
You haven't posted your error, but the class Program has no Add or Subtract methods, so I guess your error is that Add and Subtract is not found.
EDIT
And as ssd said in his answer, the static methods have to be public to be accessed from outside the class. You have not specified any access modifier, and thereby the methods will default to private.
Two things:
You need to mark Add and Subtract as public.
They are not part of class Program. So while using them in other classes than Some, you need to specify they are part of Some by using Some.Add and Some.Subtract.
Corrected Code:
namespace DelegatePrac
{
public delegate void One(int a, int b);
public class Some
{
public static void Add(int a, int b)
{
int c = a + b; Console.WriteLine("{0}",c);
}
public static void Subtract(int a, int b)
{
int c = a - b; Console.WriteLine("{0}",c);
}
}
class Program
{
static void Main(string[] args)
{
One o1,o2;
o1 = Some.Add;//gives error here
o2 = Some.Subtract;//and here!!
o1(33,44);
o2(45, 15);
Console.ReadLine();
}
}
}

Categories

Resources