All the best !!! I am trying to program in C #, but I have been pushing for several days now - I cannot call a variable from another ("a") from another class ("Class1 ').

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) { new Class1(); double b = Class1.a; Console.WriteLine("a = {0}", b); while (true) { try { string command = Console.ReadLine(); if (command == "stop") { break; } } catch (System.Runtime.InteropServices.COMException) { } } } } } 

The class from which it is necessary to take the value of the variable "a" is maximally simplified.

 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { public class Class1 { public double a = 179; } } 

I tried to google, Yandex, etc. - did not help.

  • just in case, to make the search easier, a is not a variable (local variables in C # are the values ​​that you declare inside methods). a is a field - PashaPash

1 answer 1

The problem in this line is:

 new Class1(); 

Here you create a class anonymously and therefore you can no longer access it. Need to do so:

 Class1 class1 = new Class1(); double b = class1.a; 
  • Thank!!! I understood something. Now I will continue to work on my program: this was to facilitate the perception of the issue. - ALex
  • This is not anonymous. This is just a link to the created instance is not remembered. - VladD
  • @VlaD, Yes indeed. I am confused in terminology. - trydex