How to use pointers in C#?

Hello best programmers,

I'm actually from the C/C++ corner, so maybe I'll ask a stupid question about C#. Suppose I call a function/method and give a pointer as an argument, is this possible in C# (I've read something about 'ref') and is it a good programming technique in C#? Cause what I actually want is give some arguments to a functions, which does something with those variables and than give it back modified.

Thank you!
[471 byte] By [EmbeddedC] at [2007-11-20 11:35:06]
# 1 Re: How to use pointers in C#?
In C# itself, there are no pointers. (They are under cover and you don't need to worry about them.) If you are not working with P/Invoke, or calling unmanaged code or doing some kind of magic, you don't need them.

If you realy want to work with pointers, you have to switch to unsafe mode (a block statement modifier, method modifier or global compiler option).

But in your case, it seems to me that you don't need pointers. Which you need is a reference - variable which points to an object, not to a memory address. With exception of value types (Int32, struct) every variable is reference.

The ref modifier of a parameter allows you to assign different object to the passed parameter, or modifie the place where the reference point outside the method. Look at the example:

class Model
{
public int i = 0;
}

public void Foo(Model m)
{
m.i = 1;
}

public void Bar(ref Model m)
{
m.i = 2;
m = new Model();
}

Model m = new Model();
Foo(m);
// now m.i is 1
Bar(m)
// now m.i is 0, because it points to new instance created in Bar
// the original instance of Model is now subject to GC

Was this what you were asking about? ;-)
boudino at 2007-11-9 11:36:48 >
# 2 Re: How to use pointers in C#?
Thank you very much for your reply Boudi,

Your post is very clear, I understand that I have to make everything, like variables, functions etc..., as members of a class. And when instantiated, the object becomes a reference. I begin to understand the concept now.

Thank you!
EmbeddedC at 2007-11-9 11:37:49 >
# 3 Re: How to use pointers in C#?
public unsafe void FunctionName(SomeObject* obj) {
obj->Foo();
}
MadHatter at 2007-11-9 11:38:59 >
# 4 Re: How to use pointers in C#?
I rather do the safe way, that's why C# is written for I think.
Otherwise we should go back to C++.
I must learn and understand the C# philosophy, I think that's the difficult part. To distinguish C/C++ and C# programming style.

But thank you for your posts, I've learnt from it and that's the most important thing! ;)
EmbeddedC at 2007-11-9 11:39:53 >