Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does connecting Namespaces work in C#?

Tags:

c#

I am new to C# and I am trying to print out a number from a different namespace in my main. I will provide the code below.

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("hello world" + x);
            Console.ReadLine();
        }
    }
}

namespace Applicaton
{

    class Program2
    {
        public int Test()
        {
            int x = 5;
            return x;
        }
    }
}

I want to have the x from Program2 class appear in my main which is in Program Class.

like image 372
Plam Avatar asked Jan 15 '16 20:01

Plam


2 Answers

You can modify your code like below. Since your Program2 is defined in another class, by any means you will have to fully qualify it with namespace name while accessing it.

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("hello world" + new Applicaton.Program2().Test());
            Console.ReadLine();
        }
    }
}
like image 60
Rahul Avatar answered Oct 08 '22 20:10

Rahul


First make Decalare Application as referenced namespace, then set program2 as public, set x as public properties for program2. then use class program2 in main.

Below is the source code.

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Program2 p= new Program2();
            Console.WriteLine("hello world" + p.x);
            Console.ReadLine();
        }
    }
}

namespace Applicaton
{

    public class Program2
    {
        public int x;
        public int Test()
        {
            x = 5;
            return x;
        }
    }
}
like image 45
plutomusang Avatar answered Oct 08 '22 22:10

plutomusang