Value Type and Reference Type in C#


In C#, types are divided into two main categories: value types and reference types. 



Value Types

The variables of the value types directly contain their value. Listing given below shows an example of value type int(10), struct (Book), and enum (Planets). Listing 1-5 shows how we can determine the usage of the value type in a program.


Example of Value Types

Code Snippet
  1. using System;
  2. namespace Ch01
  3. {
  4.     class Program
  5.     {
  6.         static void Main(string[] args)
  7.         {
  8.             int a = 10;               /* int type */
  9.             Book book = new Book();       /* struct type */
  10.             Planets planets = Planets.Earth;    /* enum type */
  11.         }
  12.     }
  13.     struct Book { }             /* struct type declaration */
  14.     enum Planets { Earth = 0 }   /* enum type declaration*/
  15. }

Figure 1-7 demonstrates the possible different value types.




Reference Types

In C#, the reference type is either the class type, an interface type, an array type, or a delegate type.
Listing given below shows the usage of these reference types.

Example of the Reference Types

Code Snippet
  1. using System;
  2. namespace Ch01
  3. {
  4.     class Program
  5.     {
  6.         static void Main(string[] args)
  7.         {
  8.  
  9.             IBook book = new Book();  /* book is an instance of the Book */
  10.         }
  11.     }
  12.     interface IBook { }
  13.     class Book : IBook { }
  14. }

Figure 1-8 shows the possible different reference types.


Post a Comment