Possible Duplicate:
How do I assign by “reference” to a class field in c#?
Hello everyone - tell me how to make this work? Basically, I need an integer reference type (int* would work in C++)
class Bar
{
private ref int m_ref; // This doesn't exist
public A(ref int val)
{
m_ref = val;
}
public void AddOne()
{
m_ref++;
}
}
class Program
{
static void main()
{
int foo = 7;
Bar b = new Bar(ref foo);
b.AddOne();
Console.WriteLine(foo); // This should print '8'
}
}
Do I have to use boxing?
Edit: Perhaps I should have been more specific. I'm writing a BitAccessor class, that simply allows access to individual bits. Here's my desired usage:
class MyGlorifiedInt
{
private int m_val;
...
public BitAccessor Bits {
return new BitAccessor(m_val);
}
}
Usage:
MyGlorifiedInt val = new MyGlorifiedInt(7);
val.Bits[0] = false; // Bits gets a new BitAccessor
Console.WriteLine(val); // outputs 6
For BitAccessor to be able to modify m_val, it needs a reference to it. But I want to use this BitAccessor many places, with just a reference to the desired integer.
You don't need to have a reference to an integer - just put your integer inside a reference type - which is almost what you've done already. Just change this line:
Console.WriteLine(foo);
to:
Console.WriteLine(bar.Value);
Then add an appropriate accessor to the class Bar
, and remove the compile errors (remove the ref
keywords).
An alternative approach is to pass the integer to a function by reference:
static void AddOne(ref int i)
{
i++;
}
static void Main()
{
int foo = 7;
AddOne(ref foo);
Console.WriteLine(foo);
}
Output:
8
You can't store a reference to an integer like that directly, but you can store a reference to the GlorifiedInt
object containing it. In your case, what I'd probably do is make the BitAccessor
class nested inside GlorifiedInt
(so that it gets access to private fields), and then pass it a reference to this
when it's created, which it can then use to access the m_val
field. Here's an example which does what you're looking for:
class Program
{
static void Main(string[] args)
{
var g = new GlorifiedInt(7);
g.Bits[0] = false;
Console.WriteLine(g.Value); // prints "6"
}
}
class GlorifiedInt
{
private int m_val;
public GlorifiedInt(int value)
{
m_val = value;
}
public int Value
{
get { return m_val; }
}
public BitAccessor Bits
{
get { return new BitAccessor(this); }
}
public class BitAccessor
{
private GlorifiedInt gi;
public BitAccessor(GlorifiedInt glorified)
{
gi = glorified;
}
public bool this[int index]
{
get
{
if (index < 0 || index > 31)
throw new IndexOutOfRangeException("BitAcessor");
return (1 & (gi.m_val >> index)) == 1;
}
set
{
if (index < 0 || index > 31)
throw new IndexOutOfRangeException("BitAcessor");
if (value)
gi.m_val |= 1 << index;
else
gi.m_val &= ~(1 << index);
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With