Click here to Skip to main content
15,886,720 members
Please Sign up or sign in to vote.
2.50/5 (2 votes)
See more:
How to store a ref/out variable for the class outside the function;
Consider the following code:
C#
class test
{
int data;
test(ref int orig)
{
this.data=orig;//this would pass the value of orig to data.
}
button1_Click(object sender, EventArgs e)
{
//here the value of orig has to be stored. Now if i do:
data=1;
// will 1 be passed to orig which is passed from another class?
}

but i want to store the orig's refernce in the class as this class is a form, and later on on a button click the value will be set in the orig. Now Button click event function has to set the value.
Posted

No.
int is a value type, not a reference. So when you execute
C#
this.data = orig;
the value in orig is copied into data, not a reference to the original location. (References are not pointers, although they look like them most of the time).

If you rewrote your test method to go the other way:
C#
orig = this.data;
Then the value of orig in the calling method will be changed, but subsequent changes to data outside the test method will not change it.
 
Share this answer
 
Comments
Ag_Sharad 17-Feb-13 5:39am    
no that i know but the value will not be passed by the constructor, it will be passed by other function and that fun. will be executed on a button click
Box the integer value.

Use object instead of int.
For e.g. object data;

This will pass the integer value around by reference but will require some type casting[^].

The other way would be to continue to pass the integer value (by reference) around using the ref parameter.
 
Share this answer
 
Comments
Ag_Sharad 17-Feb-13 5:40am    
i didn't get u clearly, if u could post some code......
but making int an object, will the class object variable will have the same ref, as of ref object passed as parameter.........

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900