15 - Structs in C#

15.1 Purpose of Struct in C#

Struct is an encapsulated entity. It is a value data type. All the members of struct have to be initiated. It is a simple user defined data type that can be used as an alternative to class. The struct keyword is used for creating a structure.

Structures have behaviors and attributes. They can directly contain the values of the object or instance from the stack. They support access modifiers, constructors, indexers, methods, operators, fields and properties.

15.2 Implement the Struct in C#

The struct can be defined using the struct statement. They add one or more members used in the program. The general structure for defining a struct is as shown below:

struct structure_name
{
//data members
}

Consider a Student structure to be defined. The code sample for the structure is as shown below:

public struct student
{
    public int studentid;
    public string name;
    public string course;
}

The student structure contains three members as studentid, name and course.

The implementation of structure through a code example is as shown below:

public struct student
{
    public int studentid;
    public string name;
    public string course;
};
public class Test
{
    static void Main ( string[ ] args )
    {
        student st1;
        student st2;
        st1.studentid = 1;
        st1.name = “Mark”;
        st1.course = “Management”;
      
        st2.studentid = 2;
        st2.name = “Peter”;
        st2.course = “Medical”;
        Console.WriteLine( “Student 1 id is :{0}”, st1.studentid);
        Console.WriteLine(“ Student 1 name is :{0}”, st1.name);
        Console.WriteLine(“ Student 1 course is :{0}”, st1.course);
        Console.WriteLine( “Student 2 id is :{0}”, st2.studentid);
        Console.WriteLine(“ Student 2 name is :{0}”, st2.name);
        Console.WriteLine(“ Student 2 course is :{0}”, st2.course);        
        Console.Read();
    }
}

The output for the code is as shown below:

In the above code, the student class creates two objects as st1 and st2 respectively. The objects are used for accessing the members defined in the student structure. The result is displayed using the standard output function.

The structures can be inherited from an interface in an application. The struct do not provide inheritance in C#. It is not possible for a user to inherit from a struct. The struct cannot be derived from a class.

The code for inheriting from an interface is as shown below:

class Program
{
    public interface calculate
    {
        double increment;
        void displayresult;
    }
    public struct Employee : calculate
    {
        int empid;
        double salary;
        string location;
        public Employee ( int id, double sal, string loc1 )
        {
            this.empid = id;
            this.salary = sal;
            this.location = loc1;
        }
        public void displayresult()
        {
            Console.WriteLine( “The Employee id is”+this.empid.ToString());
            Console.WriteLine(“ The salary is”+this.salary);
            Console.WriteLine(“ The location is”+ this.location);
        }
    
        public double increment()
        {
            this.salary = salary +2000.00;
        }
    }
    static void Main ( string[ ] args )
    {
        Employee e = new Employee( 201, 30000.00, “Noida”);
        e.displayresult();
        Console.WriteLine( “The incremented salary is {0}”, e.increment());
        Console.Read();
    }
}

The output for the code is as shown below:

In the above code, the interface calculate consists of two methods as increment and displayresults respectively. The methods defined in an interface can be either private or public. They cannot be used as protected. The employee struct is declared in the application. It inherits the interface. All the methods declared in the interface are used inside the structure.

In Main() method, the values for the different parameters are passed through the Employee constructor.

15.3 Use a Struct

C# struct is a light weighted as compared to the class. They are useful when simple data structures are to be implemented in an application. The struct is created on a stack. The new keyword is not used for creating it.

Features of Struct

1) A structure can implement more than one interface

2) A structure can contain methods, fields, indexer, properties, operators and events

3) A structure uses fewer resources than class as it resides on a stack

4) Structure cannot be inherited and hence they are sealed

5) A default constructor of a structure initializes every field with a default value

6) Destructors cannot be defined for a structure

7) The members of the structure cannot be defined as abstract, virtual or protected

8) The structure are implemented internally from the System.Value.Type

Class vs Structure

The differences between a class and a structure are as follows:

1) Classes are reference types and structure is value type

2) Classes have a default constructor and structure does not have it

3) Class must be instantiated with new operator but the structure does not need to be instantiated

4) There are no instance field initializes in structure but a class has in it

5) Classes can have explicit parameter less constructors but structure cannot have them

6) Classes are used to store large, complex set of data whereas structure are used for simple data

Like us on Facebook