Reference type variables

In reference type variables, the data member contains the exact address of the variable in memory. As the variable just contains a reference to the memory address, two separate reference type variables can point to the same memory address. Therefore, if a change is made to a reference type variable, the change is directly done at the memory location of the variable. Due to the change being directly made at the memory location of the variable, both variables will reflect the updated value.

The following are the reference types available in C#:

  • Class: As discussed in Chapter 1, Learning the Basics of C#, a class represents a collection of related properties and methods.
  • Interface: An interface in C# represents a collection of related properties, events, and methods, with just a declaration and no definition. In this chapter, in upcoming sections, we will deep dive into interfaces and see how they are implemented in C#.
  • Dynamic: A dynamic type variable avoids compile-time type checking. For example, if we declare a dynamics variable type and assign a variable to it, its type is defined at runtime when a value is assigned to it.

For example, in the following code snippet, we are creating a dynamics type variable, assigning different variables to it and evaluating its type at runtime:

 dynamic typeVariable = 100;
Console.WriteLine(typeVariable + " " + typeVariable.GetType().ToString());// Output 100 System.Int32
typeVariable = "Hello";
Console.WriteLine(typeVariable + " " + typeVariable.GetType().ToString());// Output Hello System.String
typeVariable = true;
Console.WriteLine(typeVariable + " " + typeVariable.GetType().ToString());// Output True System.Boolean
Console.ReadLine();
  • Object: When a new instance of a class is created using the new keyword, an object for the class is created in the memory.
  • String: A String object is a sequence of Char objects whose value is immutable or read-only. This basically implies that, when we modify a variable of type String, it creates a new object in memory.

In the next section, we will go through a code example to show how a reference type variable such as Class and a value type variable such as struct are implemented in C# and how their behavior differs.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.136.18.218