Tutorialsteacher

Follow Us

Articles
  • C#
  • C# OOP
  • ASP.NET Core
  • ASP.NET MVC
  • LINQ
  • Inversion of Control (IoC)
  • Web API
  • JavaScript
  • TypeScript
  • jQuery
  • Angular 11
  • Node.js
  • D3.js
  • Sass
  • Python
  • Go lang
  • HTTPS (SSL)
  • Regex
  • SQL
  • SQL Server
  • PostgreSQL
  • MongoDB
  • C# - Get Started
  • C# - Version History
  • C# - First Program
  • C# - Keywords
  • C# - Class and Objects
  • C# - Namespace
  • C# - Variables
  • C# - Implicitly-Typed Variables
  • C# - Data Types
  • Numbers
  • Strings
  • DateTime
  • Structure
  • Enum
  • StringBuilder
  • Anonymous Types
  • Dynamic Types
  • Nullable Types
  • C# - Value & Reference Types
  • C# - Interface
  • C# - Operators
  • C# - if else Statements
  • C# - Ternary Operator ?:
  • C# - Switch
  • C# - For Loop
  • C# - While Loop
  • C# - Do-while Loop
  • C# - Partial Class
  • C# - Static
  • C# - Array
  • Multidimensional Array
  • Jagged Array
  • C# - Indexer
  • C# - Generics
  • Generic Constraints
  • C# - Collections
  • ArrayList
  • List
  • SortedList
  • Dictionary
  • Hashtable
  • Stack
  • Queue
  • C# - Tuple
  • C# - ValueTuple
  • C# - Built-in Exceptions
  • Exception Handling
  • throw
  • Custom Exception
  • C# - Delegates
  • Func Delegate
  • Action Delegate
  • Predicate Delegate
  • Anonymous Methods
  • C# - Events
  • C# - Covariance
  • C# - Extension Method
  • C# - Stream I/O
  • C# - File
  • C# - FileInfo
  • C# - Object Initializer
  • OOP - Overview
  • Object-Oriented Programming
  • Abstraction
  • Encapsulation
  • Association & Composition
  • Inheritance
  • Polymorphism
  • Method Overriding
  • Method Hiding
  • C# - Solid Principles
  • Single Responsibility Principle
  • Open/Closed Principle
  • Liskov Substitution Principle
  • Interface Segregation Principle
  • Dependency Inversion Principle
  • Design Patterns
  • Singleton
  • Abstract Factory
  • Factory Method
Entity Framework Extensions - Boost EF Core 9
  Bulk Insert
  Bulk Delete
  Bulk Update
  Bulk Merge

C# - Struct


Updated on: June 25, 2020

In C#, struct is the value type data type that represents data structures. It can contain a parameterized constructor, static constructor, constants, fields, methods, properties, indexers, operators, events, and nested types.

struct can be used to hold small data values that do not require inheritance, e.g. coordinate points, key-value pairs, and complex data structure.

Structure Declaration

A structure is declared using struct keyword. The default modifier is internal for the struct and its members.

The following example declares a structure Coordinate for the graph.

Example: Structure
struct Coordinate
{
    public int x;
    public int y;
}

A struct object can be created with or without the new operator, same as primitive type variables.

Example: Create Structure
struct Coordinate
{
    public int x;
    public int y;
}

Coordinate point = new Coordinate();
Console.WriteLine(point.x); //output: 0  
Console.WriteLine(point.y); //output: 0
Try it

Above, an object of the Coordinate structure is created using the new keyword. It calls the default parameterless constructor of the struct, which initializes all the members to their default value of the specified data type.

If you declare a variable of struct type without using new keyword, it does not call any constructor, so all the members remain unassigned. Therefore, you must assign values to each member before accessing them, otherwise, it will give a compile-time error.

Example: Create Structure Without new Keyword
struct Coordinate
{
    public int x;
    public int y;
}

Coordinate point;
Console.Write(point.x); // Compile time error  

point.x = 10;
point.y = 20;
Console.Write(point.x); //output: 10  
Console.Write(point.y); //output: 20
Try it

Constructors in Structure

A struct cannot contain a parameterless constructor. It can only contain parameterized constructors or a static constructor.

Example: Parameterized Constructor in Struct
struct Coordinate
{
    public int x;
    public int y;

    public Coordinate(int x, int y)
    {
        this.x = x;
        this.y = y;
    }
}

Coordinate point = new Coordinate(10, 20);

Console.WriteLine(point.x); //output: 10  
Console.WriteLine(point.y); //output: 20
Try it

You must include all the members of the struct in the parameterized constructor and assign parameters to members; otherwise C# compiler will give a compile-time error if any member remains unassigned.

Methods and Properties in Structure

A struct can contain properties, auto-implemented properties, methods, etc., same as classes.

Example: Methods and Properties in Struct
struct Coordinate
{
    public int x { get; set; }
    public int y { get; set; }

    public void SetOrigin()
    {
        this.x = 0;
        this.y = 0;
    }
}

Coordinate point = Coordinate();
point.SetOrigin();

Console.WriteLine(point.x); //output: 0  
Console.WriteLine(point.y); //output: 0
Try it

The following struct includes the static method.

Example: Static Constructor in Struct
struct Coordinate
{
    public int x;
    public int y;

    public Coordinate(int x, int y)
    {
        this.x = x;
        this.y = y;
    }

    public static Coordinate GetOrigin()
    {
        return new Coordinate();
    }
}

Coordinate point = Coordinate.GetOrigin();

Console.WriteLine(point.x); //output: 0  
Console.WriteLine(point.y); //output: 0
Try it

Events in Structure

A struct can contain events to notify subscribers about some action. The following struct contains an event.

Example: Event in Structure
struct Coordinate
{
    private int _x, _y;

    public int x 
    {
        get{
            return _x;
        }

        set{
            _x = value;
            CoordinatesChanged(_x);
        }
    }

    public int y
    {
        get{
            return _y;
        }

        set{
            _y = value;
            CoordinatesChanged(_y);
        }
    }

    public event Action<int> CoordinatesChanged;
}

The above structure contains CoordinatesChanged event, which will be raised when x or y coordinate changes. The following example demonstrates the handling of the CoordinatesChanged event.

Example: Handle Structure Events
class Program
{
    static void Main(string[] args)
    {

        Coordinate point = new Coordinate();
        
        point.CoordinatesChanged += StructEventHandler;
        point.x = 10;
        point.y = 20;
    }

    static void StructEventHandler(int point)
    {
        Console.WriteLine("Coordinate changed to {0}", point);
    }
}
Try it

struct is a value type, so it is faster than a class object. Use struct whenever you want to just store the data. Generally, structs are good for game programming. However, it is easier to transfer a class object than a struct. So do not use struct when you are passing data across the wire or to other classes.

Summary

  • struct can include constructors, constants, fields, methods, properties, indexers, operators, events & nested types.
  • struct cannot include a parameterless constructor or a destructor.
  • struct can implement interfaces, same as class.
  • struct cannot inherit another structure or class, and it cannot be the base of a class.
  • struct members cannot be specified as abstract, sealed, virtual, or protected.
Related Articles
  • Structure in detail
  • Eric Lippert's blog on struct
  • Choosing between class and structure
  • Difference between Struct and Class
TUTORIALSTEACHER.COM

TutorialsTeacher.com is your authoritative source for comprehensive technologies tutorials, tailored to guide you through mastering various web and other technologies through a step-by-step approach.

Our content helps you to learn technologies easily and quickly for learners of all levels. By accessing this platform, you acknowledge that you have reviewed and consented to abide by our Terms of Use and Privacy Policy, designed to safeguard your experience and privacy rights.

[email protected]

ABOUT USTERMS OF USEPRIVACY POLICY
copywrite-symbol

2024 TutorialsTeacher.com. (v 1.2) All Rights Reserved.