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.
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();
}
}
}
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;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With