C # & ldquo; Linking & rdquo; Classes

advertisements

I'm starting a simple C# console solution via Mono on Mac OS X.

I have a Main.cs file for starters, but I want to create a separate class and be able to access object of that class from my Main.cs file.

How can I access that class from the Main.cs file?

Say my class name was Math.

In my Main.cs file, can I create a new object like so:

Math calculator = new Math()

Without referencing the class in the Main.cs file in any way?

Or, do I have to use some sort of import statement/directive?


You need a using statement if your Main and Math are in different name spaces, otherwise it just works. Below is an example. The using System brings in the library that contains the Console class, but no using is required to use the Math class.

Program.cs:

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Math caclulator = new Math();
            Console.WriteLine(caclulator.Add(1, 2));
        }
    }
}

Math.cs:

namespace ConsoleApplication1
{
    class Math
    {
        public int Add(int x, int y)
        {
            return x + y;
        }
    }
}