Wednesday, January 13, 2016

Struct in C#

A struct uses syntax similar to a class. It is a type definition. A struct type is a value type that is typically used to encapsulate small groups of related variables, such as the coordinates of a rectangle or the characteristics of an item in an inventory. The following example shows a simple struct declaration:


using System;

class Program
    public struct Book
    public decimal price;
    public string title;
    public string author;
    public bool IsAvailable;

    static void Main()
    // ... Create struct on stack.
    Book B;
    B.price = 100.00;
    B.title = "MS"; = "Vepsh";

    // ... Write struct field.

Output:- MS

  • Please notice how, in Main, the struct is created on the stack. No "new" keyword is used. It is used like a value type such as int.
  • Structs can also contain constructors, constants, fields, methods, properties, indexers, operators, events, and nested types, although if several such members are required, you should consider making your type a class instead.
  • Structs can implement an interface but they cannot inherit from another struct. For that reason, struct members cannot be declared as protected.

Means that struct stores its data in its type. It is not allocated separately on the managed heap. Structs often reside on the evaluation stack. Every program uses simple structs. All value types (int, bool, char) are structs.


Post a Comment