How could I possibly do the following:
OrderedDictionary<string, object> bag = new OrderedDictionary<string, object>();
public void Add(string str,ref object obj) {
bag.Add(str,**ref obj**);
}
So anytime I’ll want to access that specific ‘obj’ inside ‘bag’, it will refer to the passed ‘obj’ in the arguments.
Objects are already reference types. Accessing the object in your dictionary will modify the original obj.
What you have is multiple references to the same object in memory. So modifying or copying or anything like that will work correctly and persist in the same object. Keep in mind though, that if you want to set the object to something else (like null) it will only be setting the current reference to null, and not the actual object.
ref on the other hand, is useful for passing the actual reference as a parameter, and not the object in memory. Take this for example:
With this invocation:
In this situation,
obj1will still benon-nullafter the call toSomeMethod, and it will benullafter the call toSomeMethodRef.