C# - SPLessons
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

C# Structs

C# Structs

shape Introduction

In C#, structs are nothing but Structure.Structs may seem similar to classes but there are differences in both. Structs are value types variable which hold data of other types that can contain constructors, constants, fields, methods, properties, indexers, operators, events, and nested types.

shape Syntax

[attributes] [modifiers] struct identifier [:interfaces] body [;]

shape Description

Struct values are stored "on the stack" or "in-line".Structs implements interface and can be used to enhance performance.
  • Class cannot be declared using the keyword struct.
  • Structs cannot be defined with parameter-less constructor because it initializes default value.
  • A struct cannot inherit from another struct or class, and it cannot be the base of a class. Structs, however, inherit from the base class Object.
  • Struct cannot be specified with keywords like virtual,abstract and protected.
  • If the new operator is not used, the fields remain unassigned and the object cannot be used until all the fields are initialized.

shape Differences

Struct Class
Structs are value types Class are reference types
Does not support Inheritance It supports inheritance
No Explicit parameterless constructor Classes can have explicitly parameterless constructors
No default Destructor. Here the Destructor is called

shape Example

[csharp] using System; using System.Collections.Generic; using System.IO; using System.Collections; namespace SPLessons { public struct Example { public int a; public int b; public Example(int p, int q) { a=p; b=q; } } class Program { static void Main(string[] args) { Example s1=new Example(); Example s2=new Example(10,10); Console.WriteLine("Parameterless:"); Console.WriteLine("a={0},b={1}",s1.a,s1.b); Console.WriteLine("Parameter:"); Console.WriteLine("a={0},b={1}",s2.a,s2.b); } } } [/csharp] Output:e