Suppose I have a file ABC.CS
in that file I have a class ABC
as below and method Test()
:
public class ABC
{
public static void Test()
{
int a=10;
int b=11;
int c=12;
//many many variables
}
}
I want to access a
, b
... etc in another method of another class of another file say
- File :
XYZ.cs
- Class:
XYZ
- Method:
MyMethos()
.
Note: Variable may be any of type, like int
, float
, and DataTable
etc
Updated
Seems like people ignored static
keyword, please give working example
How can I do this ?
Thanks.
If you are calling the method XYZ.myMethod from Test then myMethod must be a static method. In this case for value type variables, call the method using ref for the value types.
If you need to access the variable, as it seems you need to access a Datatable, directly using the class name or the object reference, you will need to declare the variable as a class variable and make it static.
Once you've done this, try initializing the datatable in the static constructor :
Please try this out.
Theoretically you cannot do so, but if you change the method a little bit you may get what you want.
Declare a list of objects publicly and access it from the other class.
From other method, iterate the list and store them in new some variables depending on their type.
I hope this helps.
You cannot access to local vars by reflection, but you can access to static vars
You can't. You should define your variables outside of your method and make them
public
.Or if your other class inherits fromABC
then you can make themprotected
.Using static variables/functions is one thing; accessing a variable from outside of its scope is another thing.
From MSDN:
And also static variable will exist per class, not instance.
So, I assume that you will need instances of ABC class:
From another class you can call:
The other answers I've seen so far are giving what I would consider extremely bad advice.
Without more a more focused example, it's hard to say what the best approach would be. In general, you want to avoid your methods having side effects -- it makes it harder to debug and test your application. Basically, if you call the method 100 times with the same inputs, it should return the same results 100 times.
In general, a good approach is to have your methods return something that represents the results of the operation it's performing.
So, you have a class or struct that represents your return values:
And then return an instance of that class as necessary: