I'm still very new to C#, but have some experience with scripting languages such as javaScript, PHP, and VB.Net.

My question is how do I call a method from another method? Below is a chunk of code from my program. I want this method to evaluate a value and two execute one of the two methods based on the result. I'm just nit getting some of the basic fundamentals of this language and am hoping to remedy that.

static void which(int startYear, int baseYear, int StartPopulation)
        {
            if(startYear > baseYear)
            {
               startPopulation = StartPopulation(int counter, double increase, double currentPopulation)
            }
            else(startYear < baseYear)
            {
               startPopulation =  StartPopulationB(int counter, double increase, double currentPopulation);
            {    
    return startPopulation;
        }
}

The errors I'm getting are:
(1)Error 2 Method must have a return type
(2)Error 3 A namespace does not directly contain members such as fields or methods


Note: There aren't any user classes in this program.

Recommended Answers

All 2 Replies

I think you should purchase a C# book. Have a look at code-snippet.

using System;

class Test
{
    
    static int Add(int val1, int val2)
    {
        return val1 + val2;
    }
    static int Sub(int val1, int val2)
    {
        return val1 - val2;
    }

    static int MyMath(string action, int no1, int no2)
    {
        if (action == "add")
        {
            return Add(no1, no2);
        }
        else
            if (action == "sub")
            {
                return Sub(no1, no2);
            }
            else
            {
                return 0;
            }
    }


    static void Main()
    {
        int result;

        result = MyMath("add", 6, 7);
        Console.WriteLine(result);

        result = MyMath("sub", 6, 7);
        Console.WriteLine(result);

    }

In your code, "static void which..." says that you are creating a static method with no return type. You are then using "return". If your method is going to return a value you need to set its return type: "static int which" will return an integer.
Also, in your code, if you want to include more than one condition, use if..elseif...else:

if(a=b)
{
    //do something
}
else if(a!=b)
{
    //do something else
}
else
{
    //do this if none of the other conditions are met
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.