Storing a reference to a variable within a class

  • Thread starter Thread starter Christopher
  • Start date Start date
C

Christopher

Hi all,

I am trying to store a reference to a variable in my data
providerr class
but cannot save a reference to it. Can anyone help me?

I would like this code to allow me to store any field by
referenece so that
it's contents can be written to using the Value property.

Code sample:
============
public class MyField
{
private string strFieldName;
private object objValue;

public string FieldName {set{strFieldName=value;}get
{return(strFieldName);}}
public object Value {set{objValue=value;}get{return
(objValue);}}

public SqlField(string pFieldName,
ref object pObject) /* THIS LINE DOES NOT WORK AT
POINT REF */
{
strFieldName=pFieldName;
objValue=pObject;
}

Then in the program it is called using:
=======================================
int y=0;
MyField m = new MyField("id", ref y);
y=26;

Results wanted:
===============
m.Value is 0,
m.Value is 26 when y is set to 26

Please note that I don't always want to store an integer,
it maybe a string
or other object.

Thanks in advance
Chris
 
Ignoring the fact that your constructor name doesn't match the classname (I
take it you changed it before pasting it into your post), you misunderstand
the nature of value/reference types and the operating of .net
boxing/unboxing. Some beginners' info at
http://www.codeproject.com/csharp/boxing.asp and the msdn meat and two veg
is at
http://msdn.microsoft.com/library/d...ry/en-us/csref/html/vclrfboxingunboxingpg.asp .

Your code doesn't work for the same reason as...

int x = 5;
object y = x;
x = 6;

....not working as you'd hope. The variable 'y' will remain at 5. The reasons
for this is that 'x' is boxed (copied into an object, valuetype to reference
type); when 'x' is changed to 6, 'y' remains unchanged because they are not
related (and never were). If you really want to get down and dirty and use
proper pointers (why you'd want to do this is beyond me, the point of c# and
managed code is to escape that nonsense) by "pinning" variables in memory to
prevent the GC binning them while you manipulate them with pointers a la
c/c++ (see c# keywords "fixed", "unsafe" and "stackalloc" and the "*" and
"&" operators).

My advice to you is to read about boxing/unboxing/value & references types,
grab a coffee (or something stronger) and seriously rethink your program and
object model. If you need to have a single instance of a parameter being
referenced throughout your code, make a lightweight class for it, (not a
struct as they are valuetypes and will be subject to the same behaviour as
ints, bytes, strings etc). Objects, objects & objects.

Hope this helps,

- Oisin
 
Back
Top