views:

85

answers:

3

Is it possible to pass an integer as reference at class initialization and safe the reference?

class Foo {
    private int _refVal;
    public Foo(ref int val) {
        _refval = val; // saves the value, not the reference
    }
}

I could use pointers, but then I need an unsafe context.

+3  A: 

This is not possible.

Instead, you can use a class with a writable property, like this:

class Reference<T> {
    public T Value { get; set; }
    public Reference(T value) { Value = value; }
}
SLaks
Generics are not avaliable in the Microframework. But boxing/unboxing works.
chriszero
+1  A: 

Wrap it in a custom class I guess.

Itay
+3  A: 

Out of interest, why do you need to do this? One integer equal to 5 is equal to another integer equal to 5: if there is some differentiation you want to make between them, the integer value type shouldn't be used - you'd want a class instead.

This is not a direct answer to your question, but as they say improving an algorithm is better than implementing or improving a flawed one; perhaps if you could give us some more context we can help with your more general problem / task as a whole?

Hope that helps!

Kieren Johnstone
I'm try to porting a C++ lib to C# in the Microframework. They use pointers to 'link' the input and outputs of a PID controller. So they don't need to pass the variables at each loop
chriszero
Ah I see; so you're trying to replace an int*. If you wanted to just go through the code without changing algorithms you'd do well to wrap things up, see SLak's answer. However it would be better not to pass things around like this, and refactor the code. I can't think of a case where it would be best or even necessary to pass a pointer to an int like that in a modern OO language like C#. Consider using 'out' parameters, or an interface that offers a property setter. Feel free to post more code and I will do my best to offer a good alternative.
Kieren Johnstone
Well, it should be a port of an Ardunio PID lib found at http://www.arduino.cc/playground/Code/PIDLibrary. Take a look at the constructors.
chriszero
Well, use out parameters:myPID(becomes:myPID(out Input, out Output, out Setpoint, 2, 5, 1);Then, in myPID, you must assign them: rather than "*Input = x;" you'd just do "Input = x;". It's like having multiple return values from the myPID method.
Kieren Johnstone