Reader Level:
Articles

Struct in C#

By Puran Mehra on June 08, 2009
In this article, you will learn how to define structs in C#, where and how to use them and what is the difference between structs and classes.
  • 1
  • 0
  • 51881

The article explain about structs in C#.NET.


In this article, you will learn how to define structs in C#, where and how to use them and what is the difference between structs and classes.

 

struct in C# .NET

 

Struct is an encapsulated entity. Struct doesn't uses complete oops concept but are used for user defined data type. All the member of the struct has to be initialized, as it is value type.

 

A struct is a simple user-defined type, a lightweight alternative to a class. A structure in C# is simply a composite data type consisting of a number elements of other types.

 

Similar to classes, structures have behaviors and attributes. As a value type, structures directly contain their value so their object or instance is stored on the stack.

 

Struts support access modifiers, constructors, indexers, methods, fields, nested types, operators, and properties.

 

How do define struct?

 

public struct Student

        {

            int id;

            int zipcode;

            double salary;

        }

 

Note: struct members may not be declared protected.

 

Structs are simple to use and can prove to be useful at times. Just keep in mind that they're created on the stack and that you're not dealing with references to them but dealing directly with them. Whenever you have a need for a type that will be used often and is mostly just a piece of data, structs might be a good option.

 

Practical demonstration of struct

 

using System;

 

namespace example_struct

{

    class Program

    {

        public struct Student

        {

            int id;

            int zipcode;

            double salary;

 

            // all the members of the struct has to be initialized in this way

            public Student(int id, int zipcode, double salary)

            {

                this.id = id;

                this.zipcode = zipcode;

                this.salary = salary;

            }

 

            // all the members of the struct has to be initialized either in this way

            public Student(int id, int zipcode)

            {

                this.id = id;

                this.zipcode = zipcode;

                this.salary = 3400.00;

            }

 

            // if you left any member of a struct uninitialzed it will give error

            // code below will give error because the zipcode and salary field is left uninitialzed

 

            //public Student(int id)

            //{

            //    this.id = id;

            //}

 

            // struct can also have copy constructor but have to be fully initialzed

            public Student(Student x)

            {

                this.id = x.id;

                this.zipcode = x.zipcode;

                this.salary = x.salary;

            }

 

            public void DisplayValues()

            {

                Console.WriteLine("ID: " + this.id.ToString());

                Console.WriteLine("Zipcode : " + this.zipcode.ToString());

                Console.WriteLine("Salary : " + this.salary.ToString());

            }

        }

 

        static void Main(string[] args)

        {

            Student stu = new Student(12, 201301, 4560.00);

            Student stu1 = new Student(stu);

 

            stu.DisplayValues();

 

            Console.WriteLine("Copy constructor values");

            stu1.DisplayValues();

 

            Console.ReadLine();

        }

    }

}

 

Some points about structs 

  • Struct is used to improve the performance and clarity of code.
  • Struct uses fewer resources in memory than class.
  • When we have small and frequent use of some work use structs over classes.
  • Performance can suffer when using structures in situations where reference types are expected due to boxing and unboxing.
  • You should pass structs to method as ref parameters in order to avoid the performance loss associated with copying data.
  • Structs reside on the stack, so we should keep them small.
  • Structs can't be inherited and we can say they are sealed.
  • Structure implicitly inherits from System.ValueType.
  • The default constructor of a structure initializes each field to a default value. You cannot replace the default constructor of a structure.
  • You can't define destructor for structs
  • Structs can be inherited from an interface?

 Practical program showing that struct and inherit from an interface:

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace example_struct_using_interface

{

    class Program

    {

 

        public interface aa

        {

            // no access specifier is given in interface methods (by defualt they are public)

 

            double Increment();

            void DisplayValues();

        }

 

        public struct Student : aa

        {

            int id;

            int zipcode;

            double salary;

 

            public Student(int id, int zipcode, double salary)

            {

                this.id = id;

                this.zipcode = zipcode;

                this.salary = salary;

            }

 

            public void DisplayValues()

            {

                Console.WriteLine("ID: " + this.id.ToString());

                Console.WriteLine("Zipcode : " + this.zipcode.ToString());

                Console.WriteLine("Salary : " + this.salary.ToString());

            }

 

            public double Increment()

            {

                return(this.salary += 1000.00);

            }

        }

 

        static void Main(string[] args)

        {

            Student stu = new Student(12, 201301, 4560.00);

            stu.DisplayValues();

            Console.WriteLine("Salary after increment is {0}", stu.Increment());

            Console.ReadLine();

        }

    }

}

 

Structs and inheritance

 

Structs don't provide inheritance. It is not possible to inherit from a struct and a struct can't derive from any class.

 

Once exception that all type in C# is derive from the class System.Object, so structs also have the access to the methods etc., of System.Object.

 

Note: Inheritance is indirect: Structs derive from System.ValueType, which in turns derive from System.Object.ValueType adds no new method of its own, but provides overrides of some the Object methods that are more appropriate to value types.

 

Difference between structs and classes

 

structs

classes

  • structs are value type
  • classes are reference type
  • structs are stored in stack or a inline
  • classes are stored on managed heap
  • structs doesn't support inheritance
  • classes support inheritance
  • But handing of constructor is different in structs. The complier supplies a default no-parameter constructor, which your are not permitted to replace
  • Constructors are fully supported in classes

Keep you knowledge base upgraded. Hope the article would have helped you in understanding structs and their usage. Your feedback and constructive contributions are welcome.  Please feel free to contact me for feedback or comments you may have about this article.

Puran Mehra

Working as a Software professional. 

COMMENT USING

Trending up