Question how make a function and recover the return value ?

AlamaFromBe

Member
Joined
Jan 27, 2020
Messages
12
Programming Experience
10+
Hello everyone, I'm coming to you for a question that will probably seem silly to you, But I can't do a simple method (function) that returns an object and especially to retrieve it in the calling function. Kind:

C#:
int result = int myFunc () {return 25};

Or:

C#:
using System;
                  
public class Program
{
  
    public static void Main()
    {
        int result = int myFunc();
        Console.WriteLine(result);
    }
  
    int myFunc()
    {
        // Code à exécuter quand la méthode est appelée.
        return 12;
    }
}

I specify that I seek, but did not find a clear and precise answer.
 
You are trying to call an instance method from a static method without an instance. Try changing your function to static also.
 
You are trying to call an instance method from a static method without an instance. Try changing your function to static also.
Hi John, verry thanks for your speedy reply, i' come from AS3 language, i'm verry noob in C#.
Too much that I don't understand, like for example, why it has to be static, I thought that static was only to make classes usable directly without the need for an instance. But hey, I imagine that I will eventually understand .. Thanks again.
 
Your Main method is static so it doesn't know about instance members of the Program class. If you for example place it in a separate class like this:
C#:
public class Utils
{
    public int MyFunc()
    {
        return 12;
    }
}
Then you can in your static Main method create an instance of that class and call the instance method like this:
C#:
var util = new Utils();
var result = util.MyFunc();
Console.WriteLine(result);
 
As a quick aside, in C# (and Java), they are called methods. It's C and C++ which call them functions. :)
 
To quote the second sentence in that link:

Local functions are private methods of a type that are nested in another member.
 
Back
Top Bottom