Struct in C#

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? 

  1. public struct Student {  
  2.     int id;  
  3.     int zipcode;  
  4.     double salary;  
  5. }  

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 

  1. using System;  
  2. namespace example_struct {  
  3.     class Program {  
  4.         public struct Student {  
  5.             int id;  
  6.             int zipcode;  
  7.             double salary;  
  8.             // all the members of the struct has to be initialized in this way  
  9.             public Student(int id, int zipcode, double salary) {  
  10.                 this.id = id;  
  11.                 this.zipcode = zipcode;  
  12.                 this.salary = salary;  
  13.             }  
  14.             // all the members of the struct has to be initialized either in this way  
  15.             public Student(int id, int zipcode) {  
  16.                 this.id = id;  
  17.                 this.zipcode = zipcode;  
  18.                 this.salary = 3400.00;  
  19.             }  
  20.             // if you left any member of a struct uninitialzed it will give error  
  21.             // code below will give error because the zipcode and salary field is left uninitialzed  
  22.             //public Student(int id)  
  23.             //{  
  24.             // this.id = id;  
  25.             //}  
  26.             // struct can also have copy constructor but have to be fully initialzed  
  27.             public Student(Student x) {  
  28.                 this.id = x.id;  
  29.                 this.zipcode = x.zipcode;  
  30.                 this.salary = x.salary;  
  31.             }  
  32.             public void DisplayValues() {  
  33.                 Console.WriteLine("ID: " + this.id.ToString());  
  34.                 Console.WriteLine("Zipcode : " + this.zipcode.ToString());  
  35.                 Console.WriteLine("Salary : " + this.salary.ToString());  
  36.             }  
  37.         }  
  38.         static void Main(string[] args) {  
  39.             Student stu = new Student(12, 201301, 4560.00);  
  40.             Student stu1 = new Student(stu);  
  41.             stu.DisplayValues();  
  42.             Console.WriteLine("Copy constructor values");  
  43.             stu1.DisplayValues();  
  44.             Console.ReadLine();  
  45.         }  
  46.     }  
  47. }   

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 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. namespace example_struct_using_interface {  
  6.     class Program {  
  7.         public interface aa {  
  8.             // no access specifier is given in interface methods (by defualt they are public)  
  9.             double Increment();  
  10.             void DisplayValues();  
  11.         }  
  12.         public struct Student: aa {  
  13.             int id;  
  14.             int zipcode;  
  15.             double salary;  
  16.             public Student(int id, int zipcode, double salary) {  
  17.                 this.id = id;  
  18.                 this.zipcode = zipcode;  
  19.                 this.salary = salary;  
  20.             }  
  21.             public void DisplayValues() {  
  22.                 Console.WriteLine("ID: " + this.id.ToString());  
  23.                 Console.WriteLine("Zipcode : " + this.zipcode.ToString());  
  24.                 Console.WriteLine("Salary : " + this.salary.ToString());  
  25.             }  
  26.             public double Increment() {  
  27.                 return (this.salary += 1000.00);  
  28.             }  
  29.         }  
  30.         static void Main(string[] args) {  
  31.             Student stu = new Student(12, 201301, 4560.00);  
  32.             stu.DisplayValues();  
  33.             Console.WriteLine("Salary after increment is {0}", stu.Increment());  
  34.             Console.ReadLine();  
  35.         }  
  36.     }  
  37. }   

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.

Up Next
    Ebook Download
    View all
    Learn
    View all