Introduction of C# structs

Struct is a value type.It is used to encapsulate small related group of variables. Struct can implement interface but cannot inherit from another struct. Thus struct members cannot be declared as protected.
  • 2873

Introduction

Struct is a value type. It is used to encapsulate small related group of variables. Struct can implement interface but cannot inherit from another struct. Thus struct members cannot be declared as protected. Except constants and static fields we cannot initialize fields within the struct declaration. We can declare constructors with parameters for structs. All structs are inherited from System.ValueType which inherits from System.Object. Struct can be used as nullable type and can also be assigned a null value. If you want to initialize the struct members then the only way is to declare a parameterized constructor and in that constructor initialize the struct members. If you copy a struct C# creates a new copy of the object and assigns the copy of the object to a separate struct instance. The struct type is suitable for representing lightweight objects such as Point Rectangle, and Color. Although it is possible to represent a point as a class a struct is more efficient in some scenarios. For example if you declare an array of 1000 Point objects you will allocate additional memory for referencing each object. In this case, the struct is less expensive.

Example : The example demonstrates how to define a custom struct. In this case, the struct is a Rectangle with Width and Height properties, similar to what you might use to represent a rectangular shape on a screen.

Code

using System;

 class StructExample

  {

   static void Main()

      {

       Rectangle rect1 = new Rectangle();

       rect1.Width = 1;

       rect1.Height = 3    

       Console.WriteLine("rect1: {0}:{1}", rect1.Width, rect1.Height);

       Console.ReadKey();

    }

}

© 2020 DotNetHeaven. All rights reserved.