Understanding objects and references in C# – Part 1

It is sometimes quite difficult to understand the basics of Object-oriented Programming. I think the trick here is to understand every single detail. Today finally after hours of studying this subject, I can be quite confident to say that there is a simple set of rules you need to remember and try to follow. And also let’s not forget: practice makes everything perfect.

Let’s practice a bit.

Exercise 1.

int x;

int y = 2;

x = y;

So what happened in the first line? We created integer x, that has an undefined value.

In the second line we created integer y that was assigned to have a value of 2.

Third line is quite simple, we are just assigning integer x to have the same value as integer y, which is 2. Quite simple, isn’t it?

But let’s try to understand this exercise:

int x = 0;

Result r;

r = new Result();

So once again, in the first line we created integer x that has a value of 0. In the second line we created Result r that has a value of null (If you are wondering, why it is null, read my soon upcoming Part 2 of Understanding objects and references in C). In the third line now Result r has a new value and we can see that it is also calling for a class called Result. So let’s assume we have a class called Result:

class Result

{

private int score

public Result()

{

score = 10

}

public Result (int score)

{

this.score = score;

}

}

Then what do you think would be the new value of r? You can write your answers in the comments, and giving the class Result try to figure out this exercise as well:

Result r1 = new Result();

Result r2 = new Result(5);

That’s it for now with this small tutorial about Understanding objects and references in C#, if you would like to understand them better and do more complicated task, I will upload soon Part 2.