Sep 14

Still on types: reference types

Posted in Basics C#      Comments Off on Still on types: reference types

Most types introduced by the framework are reference types. So, what is a reference type? Take a look at the following code:

Student std = new Student();

When you instantiate a reference type you end up with a…yep, that’s right: a reference to the instantiated object. Notice that I said reference, not pointer. People tend to use both as synonyms, and that’s ok for most scenarios. However, if you want to be precise, there are some differences between reference and pointers. For instance, reference will support identity checks but, unlike pointers,  it cannot support all comparison operations (for instance,with pointers you can use the < and > operators,but you cannot do that with references).

Reference types are always allocated from the heap and the new operator will always return a reference for the memory that was allocated for that object. If you look at the previous snippet, that means that std will hold a reference to the memory position where the Student object was instantiated. Even though most of the types introduced by the framework are reference types, the truth is that they come with some gotchas. As you might expect, allocating memory from the heap incurs in a slight performance hit. And it might event force a garbage collection if the heap is getting “full”. Besides that, all reference types have some “additional” members associated with them that must be initialized (more on this in future posts).

In C#, all types declared using the class keyword are reference types. Here’s a possible definition for our Student type used in the previous snippet:

public class Student {
    public String Name { get; set; }
    public Int32 Age { get; set; }

There still more to say about reference types, but before that, we need to understand value types. Stay tuned for more.