Sunday, February 5, 2012

4.3. Structures, a.k.a. records

4.3.1. Definition and data access

A record is a grouping of data, called "fields", which can be of different types. They are defined with the word "struct".

In C# (unlike C), we must first declare the structure, which can not be done within "Main". Later, inside "Main", we can declare variables of this new type and use them.

The data in a "struct" can be public or private. At this moment, we are interested in those data to be accessible from the rest of our program, so we will add the word "public" before them.

From the program body we can access each field of the structure, both to read its value and to change it. To achieve this, we must specify the name of the variable and the name of the field, separated by a point:


/*---------------------------*/
/*  C# Example #39:          */
/*  example39.cs             */
/*                           */
/*  Structures               */
/*                           */
/*  Intro to C#,             */
/*    Nacho Cabanes          */
/*---------------------------*/

using System;

public class Example39
{

  struct personType
  {
    public string name;
    public char   initial;
    public int    age;
    public float  mark;
  }

  public static void Main()
  {
    personType person;

    person.name = "John";
    person.initial = 'J';
    person.age = 20;
    person.mark = 7.5f;
    Console.WriteLine("{0} is {1} years old",
      person.name, person.age);
}

Suggested exercises:
·       A "struct" to store data from a song in MP3 format: Artist, Title, Length (in seconds),  File Size (in KB). The program should ask the user for the a song's data, store them in the "struct" and then display them on screen.

 

No comments:

Post a Comment