Brian Hewitson
Brian Hewitson

Reputation: 25

passing object reference

I have an object which contains other objects that it keeps up to date. If I pass one of these sub-objects into the constructor of another class is this kept as a pointer and so identical to the object being updated?

In the below code stub I am using the EventDetails object. I do not need to modify this in the ResultsTreeViewEvent.

EventDetails eventDetails = raceDay.GetEvent(meeting, race);
ResultsTreeViewEvent newEvent = new ResultsTreeViewEvent(meet.name, eventDetails, ref treeView, fullPage, true);


public class ResultsTreeViewEvent
{
    public EventDetails race = null;

    public ResultsTreeViewEvent(String aMeetingName, EventDetails aRace, ref TreeView aTreeView, Boolean aFullPage, Boolean aShowMultiLegResults)
    {
        race = aRace;
    }

Upvotes: 0

Views: 105

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503140

If I pass one of these sub-objects into the constructor of another class is this kept as a pointer and so identical to the object being updated?

Well, it's kept as a reference - and if the object is updated via any of the references, those changes will indeed be visible via the other references, yes. You do not need to use ref for that. (It's not clear what you're trying to do with aTreeView, but you almost certainly don't want or need ref.)

References and pointers are very similar in some ways, but aren't the same. (C# does have pointers, in unsafe code, but you'll very rarely use them.)

See my articles on reference and value types and parameter passing in C# for more information.

Upvotes: 6

Related Questions