The Reference vs. Value Types with an easy to understand example

In this article I would like to use a simple example for presenting you the difference between a Reference and a Value Type. Such an example shows us how careful we have to be when dealing with properties of different types. Consider the following class and list in C#:

Reference Types

    public class Person
    {
        public string FirstName { get; set; }

        public string LastName { get; set; }
    }

and consider the following list:

    List<Person> persons = new List<Person>();

Now lets add a new Person instance into the list:

    Person person = new Person();
    person.FirstName = "Christos";
    person.LastName = "Monogios";

    persons.Add(person);

Lets now update a property in the person instance and add a new item in the persons list:

    person.FirstName = "Max";

    persons.Add(person);

The question now is whether we have two instances of the Person class inside the list. The answer is NO. If we print the FirstName of both items, we get the same result:

    Console.WriteLine(persons[0].FirstName);
    Console.WriteLine(persons[1].FirstName);

The reason for that is that the object was only created once and it was added twice in the list. When we modify a property of this one object, the change applies to both items, because both items contain a reference to the one instance of the Person Class. So keep in mind that in order to create two different objects of the Person class, you will have to use the new keyword twice!

Value Types

Lets use a similar approach as before and create a list of strings:

    List<int> ages = new List<int>();

We add a new string inside the list:

    int age = 35;

    ages.Add(age);

we update the value of age and adding it again into the list:

    age = 36;

    ages.Add(age);

Now simply print the values of this list:

    Console.WriteLine(ages[0]);
    Console.WriteLine(ages[1]);

In that case we did not affect the first item of the list, since the int type is a Value Type and the age variable contains an instance of this type, and inside the list are now two instances of type int

comments powered by Disqus