-1

So i'm trying to access one static string from classA to classB using:

    public class classB
    {

        classA ca = new classA();

        //This is the value that i want from class B
        //Here it pops the following Error:
        string B = ca.A;
    }

In the real code i need the variable from classA as static because it changes the value after i run a internal method.

if string A in classA is declared as public static Error: ClassA.A cannot be accessed with an instance reference; qualify it with a type name instead If string A in classA is declared just as static Error:ClassA.A is inaccessible due to its protection level.

public class classA
{
    static string A = "Hi";
}
Chris
  • 51
  • 1
  • 1
  • 10
  • You need to learn about C# [access modifiers](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/access-modifiers). The default access is `internal`, which means that `A is inaccessible to B`. – paulsm4 Apr 20 '20 at 05:27
  • I edit my question, actually both classes are public including the variables. – Chris Apr 20 '20 at 05:32

2 Answers2

1

By default this field in your class classA is private. You should add a public keyword to it and to the class:

public class classA
{
   public static string A = "Hi";
}

And after that, you can access property A by using patternClassName.PropertyName, in your case it's:

classA.A
kmatyaszek
  • 19,016
  • 9
  • 60
  • 65
0

You don't need an object to access a static variable

class classA
{
    public static string A = "Hi";
}
class classB
{
    string B = classA.A;
}
Shimron Duan
  • 391
  • 1
  • 3
  • 9