Visual C# Guide
Records (Structure)

The built-in data types discussed on previous pages are good enough for most of the situations where we need to store information. It becomes a bit more difficult if we need to store more than one piece of information about a thing. For example, if we were storing details of a book in a data structure, we would need to be able to store things like the following,

  • Title
  • Author
  • ISBN
  • Publisher
  • Year Published
  • Price

The first 4 items in the list are strings (ISBN can end in an X). The Year is an integer and the price a double or decimal. A single data type just won't do here.

Most programming languages include provision for a user-defined type. In Pascal, this type is called a record - this term is important as it might be used in exam questions. However, in C#, this is called a Structure. Structures can do much more than is shown in this page - but for now this is enough.

Structure Sample

class Program
   public struct TBook
      public string title;
      public string author;
      public string isbn;
      public string publisher;
      public int year;
      public double price;
   static void Main(string[] args)
      TBook book1 = new TBook();
      book1.title = "My Booky Wook"; = "Russell Brand";
      book1.isbn = "9780340936153";
      book1.publisher = "Hodder & Stoughton";
      book1.year = 2007;
      book1.price = 18.99;
      Console.WriteLine("{0} by {1}, price £{2}", book1.title,, book1.price);

Study the example carefully. The structure is declared using the keyword, struct. The structure itself consists of a series of variable declarations. We call these fields. Notice for the first time we are using the keyword public. This is important. We use this word to make sure that the variables are accessible by other parts of the program outside of the structure.

The structure declaration was written outside of the main program. Within the program, look carefully at how an instance of this structure was created and how the fields were set and read at a later time.

Structures are much more powerful than this example shows. They can have methods, including a constructor method to make it easier to initialize instances of the structure. It is normally good practice to make the fields of a structure private, and to create methods to control how values are assigned to the fields. We will deal with this idea later on. For now, it's easier to make the fields public.