Home

Fundamentals of Structures

 

Introduction

A structure is an enhanced version of the primitive data types we have used in previous lessons. Like a class, a structure is created from one variable of a primitive type or by combining various variables of primitive types.

To create a structure, you use the same formula as for a class but with the struct keyword. Here is an example of a structure:

struct Integer
{
}

Like a class, a structure can have fields. They are listed in the body of the structure. Here is an example:

struct Integer
{
    private int val;
}

A structure can also have properties. Here is an example:

Introduction
struct Integer
{
    private int val;

    public int Value
    {
        get { return val; }
        set { val = value; }
    }
}

A structure can also have methods. Here is an example:

struct Integer
{
    private int val;

    public int Value
    {
        get { return val; }
        set { val = value; }
    }

    public int Read()
    {
        return int.Parse(Console.ReadLine());
    }
}

Structure Declaration

Like any other data type, to use a structure, you can first declare a variable from it. To declare a variable of a structure, use the new operator as done for a class. Here is an example:

using System;

struct Integer
{
    private int val;

    public int Value
    {
        get { return val; }
        set { val = value; }
    }

    public int Read()
    {
        return int.Parse(Console.ReadLine());
    }
}

class Program
{
    static int Main()
    {
        Integer natural = new Integer();
	return 0;
    }
}

After declaring the variable, you can use the object the same way you would a class. You can access its members (fields, properties, and methods) using the period operator. Here is an example:

using System;

struct Integer
{
    private int val;

    public int Value
    {
        get { return val; }
        set { val = value; }
    }

    public int Read()
    {
        return int.Parse(Console.ReadLine());
    }
}

class Program
{
    static int Main()
    {
        Integer natural = new Integer();

        Console.Write("Enter a natural number: ");
        // Accessing a property of the structure
        natural.Value =
        // Calling a method of the structure
        natural.Read();

        Console.WriteLine("The value you entered was: {0}", natural.Value);
	return 0;
    }
}

Here is an example of running the program:

Enter a natural number: 248
The value you entered was: 248
Press any key to continue . . .

Although there are many similarities in the behaviors of classes and structures, you should use a structure when the object you are creating is meant to represent relatively small values. Like primitive data types and unlike a class, a structure is a value type. 

 

Home Copyright © 2006-2016, FunctionX, Inc. Next