Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C# WinForm
How to store a ref/out variable for the class outside the function;
Consider the following code:
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 17-Feb-13 0:16am
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

No.
int is a value type, not a reference. So when you execute
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:
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.
  Permalink  
Comments
Ag_Sharad at 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
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

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.
  Permalink  
Comments
Ag_Sharad at 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)

  Print Answers RSS
0 OriginalGriff 587
1 Sergey Alexandrovich Kryukov 519
2 Maciej Los 305
3 BillWoodruff 250
4 Mathew Soji 195
0 OriginalGriff 7,356
1 Sergey Alexandrovich Kryukov 6,777
2 DamithSL 5,461
3 Manas Bhardwaj 4,916
4 Maciej Los 4,475


Advertise | Privacy | Mobile
Web02 | 2.8.1411023.1 | Last Updated 17 Feb 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100