John Miller
John Miller

Reputation: 161

In C# how to call a method in a second class from the first class?

I want to call the Apple method in the Alpha class and the Beet method in the Beta class from main in Program.cs.

I can't understand what I have done wrong in the code below.

Many thanks for looking at this problem!

I have a new project with only three very simple files:

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Test
{
    class Program
    {
       static void Main(string[] args)
        {
             // Note: there are red squiggly lines under Apple and Beet  
             // in Visual Studio.
            Apple a = new Apple();            
            Beet b = new Beet();
        }
    }
}

Alpha.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Test
{
    public class Alpha
    {
        public void Apple()
        {
            Console.WriteLine("From Alpha class A module");
        }
    }
}

Beta.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Test
{
    public class Beta
    {
        public void Beet()
        {
            Console.WriteLine("From Beta class B module");
        }
    }
}

Upvotes: 1

Views: 1059

Answers (3)

Victor Bouhnik
Victor Bouhnik

Reputation: 308

You mixed the classes and methods. It should be:

Alpha a = new Alpha();
a.Apple();

Upvotes: 4

Tim Freese
Tim Freese

Reputation: 435

You need to create the objects before you can use their methods.

Alpha a = new Alpha();
a.Apple();
Beta b = new Beta();
b.Beet();

Upvotes: 3

demo
demo

Reputation: 6235

First option - declare Alpha and Beta classes as static (and methods as well). Than you can call methods in Main function

Upvotes: -3

Related Questions