How does work on Namespaces work in C #?

I am new to C # and I am trying to print a number from another 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 x from the class Program2 to appear in my main folder in the program class.

+5
source share
5 answers

Just call the class.

  Program2 p = new Program2(); Console.WriteLine(p.Test().toString()); 

and whatever programs you could call. or assign it.

 int num = p.Test(); Console.WriteLine(num); 

then print it.

+1
source

You can change your code as shown below. Since your Program2 defined in another class, in any way you have to fully qualify it with the namespace name when accessing it.

 namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Console.WriteLine("hello world" + new Applicaton.Program2().Test()); Console.ReadLine(); } } } 
+3
source

First create the Decalare application as a reference namespace, then set program2 as public, set x as public properties for program2. then use the program2 class mainly.

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" + px); Console.ReadLine(); } } } namespace Applicaton { public class Program2 { public int x; public int Test() { x = 5; return x; } } } 
+2
source

You need to instantiate the class and call the method on it.

 Program2 program = new Program2(); int x = program.Test(); Console.WriteLine("hello world" + x); 

Make sure you include the namespace:

 using Application; 
0
source

Programming doesn't act like that. Namespaces, Explore Some Object Oriented Principles.

You will need to β€œnew” or create an instance of the Program2 object, which can call the Test () method.

 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Application; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Program2 program = new Program2(); //Below I am calling the Test() method knowing that Test() will return a value to save from having to initialize another variable. Console.WriteLine("hello world" + program.Test()); } } } namespace Applicaton { class Program2 { public int Test() { int x = 5; return x; } } } 
0
source

Source: https://habr.com/ru/post/1240730/


All Articles