Reputation: 1
class ref1 = new class();
class ref2 = ref1;
What is difference between ref1
and ref2
in C# ?
Upvotes: 0
Views: 101
Reputation: 77
The first one creates a class and passes the reference to the class as value to your variable ref1. Your variable is a value and the value will contain the reference to the object.
In the second example, you create a new variable and pass onto it the value of the reference of the first variable.
In short, both variables will hold the reference to the same object when you assign then via
ClassName ref2 = ref1;
To you, they will be the same instance. You change a value in ref1, it will also change in ref2 and vice versa.
So, if you want two different objects, then you should assign them like this:
ClassName ref1 = new ClassName();
ClassName ref2 = new ClassName();
The new keyword will create a new object for you in memory.
Upvotes: 2
Reputation: 326
This is the same pointer. Changes in ref1 will be visible in ref2. Take a look on this:
http://csharppad.com/gist/ce30f0ae1a1d73bdf3ceec9e1e30b0cf
And code for this:
class test {
public int IntProperty { get; set; }
}
var ref1 = new test {
IntProperty = 12
};
var ref2 = ref1;
Console.WriteLine(ref1.IntProperty);
Console.WriteLine(ref2.IntProperty);
ref1.IntProperty = 15;
Console.WriteLine(ref1.IntProperty);
Console.WriteLine(ref2.IntProperty);
And results:
12
12
15
15
Upvotes: 0
Reputation: 83
In the case you are describing the ref1 and ref 2 are the same at creation and are both pointing to the same ojbect by reference, meaning if you use ref1
to change something, these changes are also visible in ref2
since this object is just pointing to ref1
This article should give the full story
Upvotes: 0
Reputation: 81
In this case ref1 and ref2 are pointers referring to the same object.
Ex: if you modify a property of ref2, it will affect ref1.
Upvotes: 0