Hello friends, I hope you all are doing great. In today's tutorial, we will have a detailed Introduction to Structures in C#
. It's our 17th tutorial in C# series. Structures are quite similar to classes but have few differences as well, which we will discuss today.We have discussed C# Classes
in 13th lecture, so you must read it once as we will use that knowledge in today's lecture as well. So, let's get started with Introduction to Structures in C#:
Introduction to Structures in C#
- Structure in C# is a value type data type, created by using keyword struct, and can have fields, methods, properties, operators etc. just as in C# Classes.
- Main difference between C# Class & Structure is that C# Class is a Reference Type Date type while C# Struct is a Value Type Data type.
- Let's have a look at the syntax of C# Structure:
- You can see in above figure, that we have created a struct in C# named StudentsData and it has two private fields in it i.e. ID and Name.
- This structure declaration is quite similar to that of C# class and the only difference is that we have used struct keyword here, instead of class keyword.
- So, now let's add a C# Method in this structure and then invoke it from Main Function, shown in below figure:
- So, you can see in above figure that we have invoked structure in the same way as we invoked C# Class.
- We have first created a reference variable for C# structure and then invoked the Structure Method. ( as we did for C# Class )
- We can't inherit a structure from a Parent Class or any other struct but we can inherit a class from a structure.
- Both Structs & Classes can inherit from an Interface. ( which we will study in next lecture)
- C# Data Types i.e. int, float, double are examples of Struct in C#.
- Structs are stored on Stack while we use Heap for storing C# Classes.
- Let's have a look at Struct Constructor, which is slightly different than Class Constructor:
Struct Constructor in C#
- Structures in C# can't have destructors, if you add a destructor in struct, then compiler will generate an error.
- Although you can create a Constructor in C# Struct but make sure it has some parameters in its definition.
- A parameter-less constructor is not allowed in Structures but you can overload Struct Constructors.
So, that was all about Structures in C# and you must have noticed that they are just Value Type version of C# Classes, which are actually Reference Type. In the next lecture, we will have a look at Interface in C#. Till then take care & have fun !!! :)