Tuesday, February 7, 2012

4.3.3. Nested structs

We may find a record which contains several data, and also that one of these data is made up of several simpler data. For example, a birth date could be formed by day, month and year. It would become a "struct" which contains another "struct":

/*---------------------------*/
/*  C# Example #41:          */
/*  example41.cs             */
/*                           */
/*  Nested structs           */
/*                           */
/*  Intro to C#,             */
/*    Nacho Cabanes          */
/*---------------------------*/

using System;

public class Example41
{

  struct birthDate
  {
    public int  day;
    public int  month;
    public int  year;
  }


  struct personType
  {
    public string name;
    public char   initial;
    public birthDate birthday;
    public float  mark;
  }

  public static void Main()
  {
    personType person;

    person.name = "John";
    person.initial = 'J';
    person.birthday.day = 15;
    person.birthday.month = 9;
    person.mark = 7.5f;
    Console.WriteLine("{0} was born in month {1}",
      person.name, person.birthday.month);    
    }
}

Suggested exercises:
·       Expand the program of the first part of 4.3.2, so that the "length" is stored as minutes and seconds, using a nested "struct".

No comments:

Post a Comment