-
Reference question
Hello all,
Not that long ago I started with C# with already a lot of experience in vb.net and java. I came to face a problem with storing the same reference to for an Int32(or what ever) value.
Ill explain:
Class1 has a variable: Int32 myInt = 0; I want to pass this to the constructor of Class2(these are instances of different classes) with the REF keyword. Now in the constructor I want to pass this myInt to class2.myRefInt.
Code:
class Class2{
Int32 myRefInt;
public Class2(ref Int32 myRefInt){
this.myRefInt = myRefInt;
}
}
//somewhere in the code
Int32 myInt = 2;
Class2 c2 = new Class2(ref myInt);
myInt = 5;
Console.writeline(c2.myRefInt); // This gives 2 back while I thought I passed the reference to class2. Wich should mean that it should get its Int32 from the same position in the memory and therefor be 5 aswell.
I hope people can help me with this.
Greets
-
Re: Reference question
You misunderstand what the 'ref' keyword means. What it does, and all it does, is allow you to assign a new value to the parameter inside the method and have that change affect the original argument too. That's it, that's all. It doesn't magically make your value type object behave as a reference type object, not that what you're expecting there would work for reference types anyway. It also doesn't magically turn your values into pointers.
If you want that behaviour then you will need to actually use pointers, which C# does support. That said , I doubt that that's really what you need. You probably just need an reference type object, i.e. an instance of a class, with an Int32 property.
-
Re: Reference question
Thanks for your reply, I was already afraid I needed to do something like that. Solved it now by using an Interface with a properties I change.
The reason for this is that I wanted to create a rule system on variables and therefor needed their location.
Well in anycase, solved.