Tam Coton
Tam Coton

Reputation: 874

C# check I'm understanding assignation right

So I'm learning C#, and I've been having a bit of trouble with a program I'm writing. I just wanted to check that I'm understanding variable assignation right. Does the following behave like I think?

SomeObject someObject; // declares a SomeObject object called someObject
SomeObject someReference; // declares a SomeObject object called someReference
SomeObject someOtherObject; // declares a SomeObject object called someOtherObject

someObject = new SomeObject(); // initialises a new SomeObject object into someObject using SomeObject's contructor
someOtherObject = new SomeObject(); // initialises a new SomeObject object into someOtherObject using SomeObject's constructor
someReference = someObject; // someReference is now a reference pointing to the same place as someObject

someReference.attribute = value; // sets someReference's attribute attribute to value. someObject.attribute is also now value

someReference = someOtherObject; // someReference now points to someOtherObject instead of someObject
someReference.attribute = value2; // someOtherObject.attribute is now value2. someObject.attribute is unaffected

someReference = null; // sets someReference to be a null reference. someObject and someOtherObject are unaffected.

Upvotes: 3

Views: 111

Answers (1)

Fabjan
Fabjan

Reputation: 13676

I would slightly change some of your comments that seem a little inaccurate at least to me (others comments are all right):

// declares a field (if it's in class) or a variable (if it's inside method) 
// of type SomeObject that will later work with SomeObject instance

SomeObject someObject; 

...

// instantiates a new SomeObject instance (including creation of object on heap, 
// pointer to this object and running object constructor). 
// It also makes someObject point to this newly created object.

someObject = new SomeObject(); 
...

// sets new value for someReference's 'attribute' field (or property)

someReference.attribute = value; 

...

Upvotes: 1

Related Questions