I need to reference the value of a variable in a different method, class, and file than the one I am currently in. I am brand new to C# and still trying to get these concepts.
Basic structure I have:
namespace Planning
{
public class Service
{
public bool AddRoute(l, m, n)
{
bool variable = xyz;
}
}
}
And I need to access that variable from a completely different file. I have looked at several questions already posted here but not of them deal with the exact level I am trying to access or how to access the variable from a method with parameters that I cannot access at that time.
Can this not be done with a public property?
I hope i will not confuse you even more.
The "variable in the other class" should be a property of that class. You need to make sure it is public, and then, you need the
AddRoute
method get an instance of that class with that property set. You could then access the property value using something likeotherClassInstance.xyz
.If the above confuses you, I suggest starting at the beginning, learning about Object Oriented Programming before attempting any coding at all.
Short answer: you can't, period.
What you can do is set a
public
member variable:But public member variables are frowned-upon, with good reason.
Better yet, add a read-only property that returns the value of a private member variable:
Then from elsewhere:
In your case, you can set that variable as return parameter of your method:
Call from different class:
Now value of your variable from AddRoute method is inside otherVariable in another class.