In a class (ClassA) of mine I want to create a related instance of another class (ClassB) providing it with a reference to the object who has initiated it's creation. So I've provided ClassB with a construcror taking a (ref ClassB parent) argument. But in ClassA I can't just call var child = new ClassB(ref this). How to implement this?
The ref keyword causes Pass by Reference semantics - that is, if the variable is re-assigned in the called function, it will re-assign the variable in the caller as well.
Obviously, this only works if a variable2 (which can be re-assigne to) is directly passed as the argument and will not work if an arbitrary expression is passed. In this case, this is not a variable, rather a special expression which cannot be re-assigned, and so cannot be used.
As such, this would work: (But please see other answers and keep reading as to why this is likely not required and/or just silly.)
var me = this;
var other = new ClassB(ref me);
However, Pass by reference should not be confused with Pass by Object [Sharing]1 semantics. Pass by Object means that if an object is passed, that object is passed: the object is not copied/cloned/duplicated. If the object is mutated then the object is mutated. All Reference Types have Pass by Object semantics in C# unless either ref or out are used. (The class keyword declares a new reference type, as in the case in the post).
On the other hand, Value Types (e.g. struct), including int and Guid and KeyValuePair<K,V>, have Pass by Value semantics - in this case a copy is made and thus, if the value is modified, only the value struct (which is a copy) changes.
Happy coding
1 Underneath C#/.NET achieves Pass by Object by passing a reference to an object by Value. However, the rules above correctly describe the observable semantics and effects.
2 Unlike C#, which only allows variables to be used with ref, VB.NET allows Properties to be used. The VB.NET compiler automatically creates a temporary variable and implicit reading/writing instructions of the property during compilation.
ref refers to variable references, not object references.
If you just want to pass a reference to an object, the ref keyword isn't necessary. Objects are already reference types, so it's their references being passed by value. The objects themselves aren't copied.
So, you neither need the ref keyword in the constructor nor in the instantiation:
public ClassB(ClassA parent)
{
}
var child = new ClassB(this);
You don't need to pass by ref in this case. If you are passing ClassB(this), it will be passed by reference and not by value anyway.
Any changes made to the classA instance passed into classB's constructor will be applied to class A as well.
Do you really need the ref keyword? All the types are basically passed by reference, so if you have ClassB take ClassA as constructor argument, just pass new ClassB(this), no need to use ref.
You can't change the this pointer, which is something that the ref keyword allows. Why can't you declare ClassB like this?
ClassA m_classA;
public ClassB(ClassA classA)
{
m_classA = classA;
}
Related
This question already has answers here:
When to use ref and when it is not necessary in C#
(9 answers)
Closed 3 years ago.
I get that you wouldnt use them if you actually want a value-type to be passed by value, but why dont we always use parameters when passing a reference type?
Wouldnt that make it more readable since it would make it very clear whats happening in the function from just the parameters, especially when dealing with immutable objects like strings?
Or is there some downside to this approach i dont see?
EDIT: I thought passing reference types implicitly passed by reference, so I thought passing "ref ReferenceType" and "ReferenceType" did the same thing, which I now know it doesnt, thanks for making me understand. I found this linked article the most helpful in unerstanding the differences(Im quite the visual learner): http://www.leerichardson.com/2007/01/parameter-passing-in-c.html
You seem to be confusing reference types with reference parameters.
Examples of reference types are classes, arrays, and strings. When you pass a class, say, as a parameter you are really passing a pointer to the class, so the method works (via the pointer) on the original object.
If you pass, say, an int as a non-ref parameter it is copied. Instead, if you add a ref, a pointer to it is passed just as if it had been a class. Modifications to non-ref value parameters are invisible outside the called method (you operate on the copy). With ref parameters, on the other hand, you operate on the original variable.
Passing a reference type as a reference parameter gives you double indirection, which allows you to modify what the reference points to in the calling scope at the cost of additional overhead when accessing the referenced instance itself.
Sounds like you are referring to the ref keyword.
Here's two examples showing that using the keyword does make a difference.
Without ref:
void SomeMethod(SomeObject someObject)
{
someObject = new SomeObject(); // Assignment is only local to the method scope
}
var someObject = new SomeObject();
var sameObject = someObject;
SomeMethod(someObject);
bool same = someObject == sameObject; // true
With ref:
void SomeMethod(ref SomeObject someObject)
{
someObject = new SomeObject(); // Assignment affects the outer scope due to ref
}
var someObject = new SomeObject();
var sameObject = someObject;
SomeMethod(someObject);
bool same = someObject == sameObject; // false
Using the ref keyword passes the variable pointer as well as the object, so reassigning inside the method affects the variable outside the method.
As well as ref there is also in and out; more details here.
How c# references work if, classes are references
class1 a = new class1();
so address named "a" contains
address of the object indicating mem[0] ,So it's a pointer
why
method(class1 a);
copies value of object to a local method instance and not address of mem[0]?
does it implicitly de-reference (*) a?
if so ,then ref modifier cancels it?
lets say a class defines a type of an address to addresses that point to various points of an object. i still cant get to the end of it...
why method(class1 a) copies value of object to a local method
This is a wrong assumption. The method parameter a contains a reference to the object. If you use method(ref class1 a), then you get a reference to the variable passed to the method, which in turn contains a reference to the object
Given
class1 a = new class1();
method(ref a);
In the method, you could assign a new object to the parameter and this would change a!
void method(ref class1 b)
{
b = new class1(); // This changes a!
}
If the ref keyword is missing, the method gets a copy of the reference (not a copy of the object!)
void method(class1 b)
{
b = new class1(); // This does NOT change a.
// But
b.IntProperty = 5; // This changes a property of a.
}
In C# you don't have to use *. C# knows which types are reference and which ones are value types and treats them accordingly.
For a normal parameter:
For value types: a copy of the value is passed.
For reference types: a copy of the value is passed (yes!). The value just happens to be a reference (or null). I.e., no object is copied.
For ref parameters:
For value types: a reference to the variable containing the value is passed.
For reference types: a reference to the variable containing a reference (or null) is passed.
In other words, for ref parameters, the parameter name is just an alias for the variable used in the method call.
If you find this confusing, it helps to configure the colors in the editor to help to differentiate between reference and value types. In Visual Studio: Go to menu Tools > Options..., then Environment > Fonts and Colors and change the color of User Types - Structures (i.e. of value types) to display as a different color as classes (I am using Olive). There are a few other User Types you can change (I am using Red for delegates, a dark Orange for enums, Purple for interfaces and a kind of neon green for type parameters.
Yes you may want to think about C# class variables as (safe) C pointers, in this sense. They just don't allow you to manipulate where they point in memory (the run-time is even allowed to re-allocate and move them).
If your class1 is a class type (as opposed to a struct type or ValueType), then you are however not correct that method will copy the whole a object. It will instead act as if you had passed a pointer in C. But just like in C, *p1==*p2 and p1==p2 but &p1!=&p2
Since class variables store mere references (similar to C pointers), if method mutates the object referred by a, these mutations will remain after method returns. Passing a class variable by ref is then analogous to passing a pointer to a pointer in C; but it can hardly ever be a good design idea in C#.
This is how class variables behave (including strings). However there are also value types (all basic types except string and object, and structs) which are copied when assigned or passed to methods, unless passed with a qualifier such as ref or out.
Further reading:
Value vs Reference Types
MSDN: Reference types
MSDN: Value types
You will have to understand how methods are called and how objects are allocated in the memory.
All class types are of reference types in C# - inheriting from System.Object.
Supports all classes in the .NET Framework class hierarchy and
provides low-level services to derived classes. This is the ultimate
base class of all classes in the .NET Framework; it is the root of the
type hierarchy.
Reference: MSDN Documentation of System.Object
Meaning, they would be allocated in heap. Their reference would be copied to some place. The variable holds that place where the reference is copied.
In case of method call, the address of an object is copied to call stack. It is pointing to the same address.
So if you change any property (of value type) of the class, you will still be able to access the changed value in the caller method - even though you don't use ref keyword.
void Method(Class A)
Technically, ref keyword provides same address location - instead of copying this address to new location.
Hope this answers your query.
I found it difficult to come up with a descriptive enough title for this scenario so I'll let the code do most of the talking.
Consider covariance where you can substitute a derived type for a base class.
class Base
{
}
class Derived : Base
{
}
Passing in typeof(Base) to this method and setting that variable to the derived type is possible.
private void TryChangeType(Base instance)
{
var d = new Derived();
instance = d;
Console.WriteLine(instance.GetType().ToString());
}
However, when checking the type from the caller of the above function, the instance will still be of type Base
private void CallChangeType()
{
var b = new Base();
TryChangeType(b);
Console.WriteLine(b.GetType().ToString());
}
I would assume since objects are inherently reference by nature that the caller variable would now be of type Derived. The only way to get the caller to be type Derived is to pass a reference object by ref like so
private void CallChangeTypeByReference()
{
var b = new Base();
TryChangeTypeByReference(ref b);
Console.WriteLine(b.GetType().ToString());
}
private void TryChangeTypeByReference(ref Base instance)
{
var d = new Derived();
instance = d;
}
Further more, I feel like it's common knowledge that passing in an object to a method, editing props, and passing that object down the stack will keep the changes made down the stack. This makes sense as the object is a reference object.
What causes an object to permanently change type down the stack, only if it's passed in by reference?
You have a great many confused and false beliefs. Let's fix that.
Consider covariance where you can substitute a derived type for a base class.
That is not covariance. That is assignment compatibility. An Apple is assignment compatible with a variable of type Fruit because you can assign an Apple to such a variable. Again, that is not covariance. Covariance is the fact that a transformation on a type preserves the assignment compatibility relationship. A sequence of apples can be used somewhere that a sequence of fruit is needed because apples are a kind of fruit. That is covariance. The mapping "apple --> sequence of apples, fruit --> sequence of fruit" is a covariant mapping.
Moving on.
Passing in typeof(Base) to this method and setting that variable to the derived type is possible.
You are confusing types with instances. You do not pass typeof(Base) to this method; you pass a reference to Base to this instance. typeof(Base) is of type System.Type.
As you correctly note, formal parameters are variables. A formal parameter is a new variable, and it is initialized to the actual parameter aka argument.
However, when checking the type from the caller of the above function, the instance will still be of type Base
Correct. The argument is of type Base. You copy that to a variable, and then you reassign the variable. This is no different than saying:
Base x = new Base();
Base y = x;
y = new Derived();
And now x is still Base and y is Derived. You assigned the same variable twice; the second assignment wins. This is no different than if you said a = 1; b = a; b = 2; -- you would not expect a to be 2 afterwards just because you said b = a in the past.
I would assume since objects are inherently reference by nature that the caller variable would now be of type Derived.
That assumption is wrong. Again, you have made two assignments to the same variable, and you have two variables, one in the caller, and one in the callee. Variables contain values; references to objects are values.
The only way to get the caller to be type Derived is to pass a reference object by ref like so
Now we're getting to the crux of the problem.
The correct way to think about this is that ref makes an alias to a variable. A normal formal parameter is a new variable. A ref formal parameter makes the variable in the formal parameter an alias to the variable at the call site. So now you have one variable but it has two names, because the name of the formal parameter is an alias for the variable at the call. This is the same as:
Base x = new Base();
ref Base y = ref x; // x and y are now two names for the same variable
y = new Derived(); // this assigns both x and y because there is only one variable, with two names
Further more, I feel like it's common knowledge that passing in an object to a method, editing props, and passing that object down the stack will keep the changes made down the stack. This makes sense as the object is a reference object.
Correct.
The mistake you are making here is very common. It was a bad idea for the C# design team to name the variable aliasing feature "ref" because this causes confusion. A reference to a variable makes an alias; it gives another name to a variable. A reference to an object is a token that represents a specific object with a specific identity. When you mix the two it gets confusing.
The normal thing to do is to not pass variables by ref particularly if they contain references.
What causes an object to permanently change type down the stack, only if it's passed in by reference?
Now we have the most fundamental confusion. You have confused objects with variables. An object never changes its type, ever! An apple is an object, and an apple is now and forever an apple. An apple never becomes any other kind of fruit.
Stop thinking that variables are objects, right now. Your life will get so much better. Internalize these rules:
variables are storage locations that store values
references to objects are values
objects have a type that never changes
ref gives a new name to an existing variable
assigning to a variable changes its value
Now if we ask your question again using correct terminology, the confusion disappears immediately:
What causes the value of a variable to change its type down the stack, only if it's passed in by ref?
The answer is now very clear:
A variable passed by ref is an alias to another variable, so changing the value of the parameter is the same as changing the value of the variable at the call site
Assigning an object reference to a variable changes the value of that variable
An object has a particular type
If we don't pass by ref but instead pass normally:
A value passed normally is copied to a new variable, the formal parameter
We now have two variables with no connection; changing one of them does not change the other.
If that's still not clear, start drawing boxes, circles and arrows on a whiteboard, where objects are circles, variables are boxes, and object references are arrows from variables to objects. Making an alias via ref gives a new name to an existing circle; calling without ref makes a second circle and copies the arrow. It'll all make sense then.
This is not an issue with inheritance and polymorphism, what you're seeing is the difference between pass-by-value and pass-by-reference.
private void TryChangeType(Base instance)
The preceding method's instance parameter will be a copy of the caller's Base reference. You can change the object that is referenced and those changes will be visible to the caller because both the caller the callee both reference the same object. But, any changes to the reference itself (such as pointing it to a new object) will not affect the caller's reference. This is why it works as expected when you pass by reference.
When you call TryChangeType() you are passing a copy of the reference to "b" into "instance". Any changes to members of "instance" are made in the same memory space still referenced by "b" in your calling method. However, the command "instance = d" reassigns the value of the memory addressed by "instance". "b" and "instance no longer point to the same memory. When you return to CallChangeType, "b" still references the original space and hence Type.
TryChangeTypeByReference passes the a reference to where "b"'s pointer value is actually stored. Reassigning "instance" now changes the address that "b" is actually pointing to.
We know that class are reference types, so in general when we are passing a type, we are passing a reference but there's a difference between passing just b and ref b, which can be understood as:
In first case 1 it is passing reference by value, which means creating a separate pointer internally to the memory location, now when base class object is assigned to the derived class object, it starts pointing to another object in the memory and when that method returns, only the original pointer remains, which provides the same instance as Base class, when the new pointer created is off for garbage collection
However when object is passed as ref, this is passing reference to a reference in memory, which is like pointer to a pointer, like double pointer in C or C++, which when changes actually changes the original memory allocation and thus you see the difference
For first one to show the same result value has to be returned from the method and old object shall start pointing to the new derived object
Following is the modification to your program to get expected result in case 1:
private Base TryChangeType(Base instance)
{
var d = new Derived();
instance = d;
Console.WriteLine(instance.GetType().ToString());
return instance;
}
private void CallChangeType()
{
var b = new Base();
b = TryChangeType(b);
Console.WriteLine(b.GetType().ToString());
}
Following is the pictorial reference of both the cases:
When you do not pass by reference, a copy of the base class object is passed inside the function, and this copy is changed inside the TryChangeType function. When you print the type of the instance of the base class it is still the of the type "Base" because the copy of the instance was changed to "Derived" class.
When you pass by referece, the address of the instance i.e. the instace itself will be passed to the function. So any changes made to the instance inside the function is permanent.
Quick question :
I am passing a class (reference type) to a method without using the "ref" keyword. Thus, the reference itself to my class is passed by value.
Then, I change the reference of my class (I make the reference point to another instance defined inside my method).
Finally, I return the initial method. However, in this case the returned instances points to the instance of the second class.
public Class Foo(Class A)
{
Class B = new Class();
A = B;
return A;
}
Foo returns a references pointing to B !
I am a little bit confused, since when doing A = B I make the reference of A point to another reference, or A's referenced is passed by value.
EDIT 1
Thanks for the response, but If I take the following example the change is not reflected. Indeed, I am trying to change the references of A but A's references is passed by value so in this case I understand why the change is not reflected..
void Foo(Class A)
{
A = null;
}
Many Thanks.
Basically, when you're passing an object, a reference is passed:
When an object of a reference type is passed to a method, a reference to the object is passed. That is, the method receives not the object itself but an argument that indicates the location of the object. If you change a member of the object by using this reference, the change is reflected in the argument in the calling method, even if you pass the object by value.
You can read more on this MSDN page.
You can read more on the other answers, but do notice that you're returning a class. Usually you'll return a specific object type, and when you won't be so free to do silly things like that. (of course, assuming that B inherits from A, you could create a new B inside the method and return it, which will be valid, but still, it's not making sense).
Another thing you might want to remember is the ref and out.
ref will expect an initialized value, and that value is changed in the method.
out doesn't care what it gets in, but you need to initialize and set it in the method.
Other than that, and the other answers here, either be more specific with your question and code, or have a read at the different links in the answers :)
You are passing a reference - an immutable value - into the method using the mutable variable, more precisely a parameter, A. Then you assign to the mutable variable A a new value, the immutable reference to the newly created object. Finally you are returning the current value of the variable A which at that point is the reference to the new object and no longer the reference to the object you passed into the method.
Essentially you are confusing the variable and the value stored in that variable. At no point did you change any reference, you only exchanged the value, i.e. reference, stored in the variable.
When you pass reference type by value the attempt to reassign the parameter to a different memory location only works inside the method and does not affect the original variable.
Check out Passing reference - type parameters .
using c#, vs2008, winforms
If i am passing a parameter via a property to a child form from a parent form, or infact via a property to any class, and the the paramater im passing in C# is a reference type created in the parent form,
does it get passed as a ref or value by default ?
Eg if i pass a dataset via a property.
And if it does get passed by value, can you make it passed by ref via a property ?
Or should i just pass it via a method paramater, is that better practice ?
Basicaly i want to retrieve a populated object back to the parent form, and feel passing by ref an object that is created in the parent form is better.
For reference types, a reference to the variable is passed by value. Unless, of course, you use the ref or out keywords in C# to alter that behaviour.
That means that a DataSet-valued property passes, in actual fact, a reference to a DataSet instance, and passes it by value.
Jon Skeet's "C# in Depth" is a great reference (no pun intended) on these matters.
It is important to note that pass by reference in C# has a specific meaning. In the case of a property, the property ends up pointing to the same address as that of the object it was set to. In the case of passing objects to a function, C# uses pass reference by value semantics. That means that the reference itself is copied, so a new pointer points to the same address as the object that was passed. This prevents a function from nullifying any original pointer by setting its parameters to null. To actually pass an original reference, the 'ref' keyword must be used:
class SomeClass
{
public object MyObjectProperty { get; set; }
}
var someClass = new SomeClass();
object someObject = new object();
someClass.MyObjectProperty = someObject; // Makes MyObjectProperty point to the same location as someObject
In the following case, reference by value semantics are used:
void MyMethod(object someObject)
{
someObject = null;
}
object someObject = new object();
MyMethod(someObject);
Console.WriteLine(someObject == null); // Prints false
In the following case, actual pass by reference semantics are used:
void MyMethod(ref object someObject)
{
someObject = null;
}
object someObject = new object();
MyMethod(ref someObject);
Console.WriteLine(someObject == null); // Prints true
The first thing to understand is that, in .Net, a variable can be either a value type (e.g int) or a reference type (a class). Value type variables point directly to a value in memory, whereas reference type variables point to a memory location.
By default, parameters are passed by value. However, remember that the 'value' of a reference type is actually its location in memory. So even though it's called passing by value, you are really passing a reference to a particular class.
C# does not pass by reference in the same way that C++ does. It is more accurate to say that it passes by reference value (for reference types anyways).
Read this by Jon Skeet