Home > front end >  Access a public variable from a private class in a different .cs file C#
Access a public variable from a private class in a different .cs file C#

Time:07-12

I want to access a public variable "Program" which is public string Program { get; set; } from a private class (in a cs file called Login.cs) i.e.

`private void Computer(string directory)
 {
 Program = directory;
 //more code
 }`

I want to get this variable in a file called Disk.cs. What are the ways I can go about this?

CodePudding user response:

Probably not the answer you're looking for but if there is no need to have a private class you could just change it to public and avoid the issue very quickly. If not then I will follow up. You have also most likely already seen this however I wanted to point you to the documentation on access modifiers incase you wanted to look into this more: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/access-modifiers

(REPLY TO COMMENT) You sure can if you change the return type of your method from void to something like string or int (depending on the data you want) you can just do the following:

var myVariable = ThePublicMethodOnThePrivateClass(); 

CodePudding user response:

You could have a public static property in the Program class and access it as Program.myProgram but that looks pretty ugly. Probably better to have a public static class that contains public static properties for your global variables (see below)

Use leading namespace qualifiers too if needed

public static class globalVars
{
    public static string myProgram = "";
}

Check out this fiddle for an example https://dotnetfiddle.net/cVZqrX

  • Related