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 16-Feb-13 23:16pm
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.........
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

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

  Print Answers RSS
0 Sergey Alexandrovich Kryukov 474
1 Maciej Los 375
2 OriginalGriff 263
3 CPallini 214
4 Peter Leow 200
0 OriginalGriff 6,152
1 Sergey Alexandrovich Kryukov 5,312
2 Maciej Los 3,279
3 Peter Leow 3,184
4 DamithSL 2,490


Advertise | Privacy | Mobile
Web03 | 2.8.140721.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