One of the factors that make the knowledge of programming languages a highly employable skill is the fact that this knowledge helps you create and mold how the world views digital content. That is quite the power to have. C# is one of these programming languages that also provides great scope for customization, modification, and usability. In today’s article, we will be taking you through everything you need to know about a C# Struct and why it is so important.
Before we delve into the importance of C# structs, let us first understand what it means.
Table of Contents
What is a C# Struct?
As implied, the term ‘struct’ is a shorter version of the word ‘structure’. A structure gives you the ability to create your own data type. For instance, if you had to create a code that represents a book, no single data type will be adequate. You will need multiple data types to represent various factors of the book like, size of the book, dimensions of the book, manufacturing brands, and more.
In essence, C# structs are extremely similar to classes. Structs can use variables, methods, and constructors within them. There are some differences as well, which we will dive into later in this article.
Structures are known to be of value types instead of reference types. This is because structures contain variables that have direct values instead of a reference point to a specific value within the program memory.
How to use a C# Struct?
Considering the above example of the book, we can define different features of the book using separate data types. Like the following example, you would have to explicitly declare and define each value for the item, in this case, a book.
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace Struct
{
class Program
{
static void Main(string[] args)
{
string Brand;
int Pages;
float Weight;
string Dimensions;
Console.WriteLine("What is the brand?");
Brand = Console.ReadLine();
Console.WriteLine("What is the page count?");
Pages = int.Parse(Console.ReadLine());
Console.WriteLine("What is the weight?");
Weight = float.Parse(Console.ReadLine());
Console.WriteLine("What is the dimensions?");
Dimensions = Console.ReadLine();
}
}
}
The problem with this method is that this method only satisfies an individual object’s parameters. If you need to declare and define the characteristics of multiple books, then you will be forced to do this entire process all over again, for every single instance. This is where C# structs come into play. The structs contain all the defining characteristics of an object so that you don’t have to reiterate the same parameters individually and repeatedly.
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace Struct
{
class Program
{
struct Book
{
public string Brand;
public int Pages;
public float Weight;
public string Dimensions;
}
static void Main(string[] args)
{
Book book1;
Console.WriteLine("What is the brand?");
book1.Brand = Console.ReadLine();
Console.WriteLine("What is the page count?");
book1.Pages = int.Parse(Console.ReadLine());
Console.WriteLine("What is the weight?");
book1.Weight = float.Parse(Console.ReadLine());
Console.WriteLine("What is the dimensions?");
book1.Dimensions = Console.ReadLine();
}
}
}
The above example is with the use of a struct. By creating a C# struct, you can very easily associate a certain set of attributes or parameters to one particular struct and then use that struct to define multiple objects. This is why structs play such an important role in coding. They simplify manual coding and allow the programmers or developers to code quicker, with more precision and less margin of error.
How to use a C# Struct Constructor?
Unlike C++, in C# we cannot use a struct constructor within a struct if it does not have any parameters. A struct in C# may only have a static struct or one with parameters. Once you begin, you must remember to mention every element of the struct within the struct constructor that has parameters and assign these parameters to each element as you will be thrown an exception by the compiler if this is not done. The following example shows you how this can be done.
using System;
public class Program
{
public static void Main()
{
Number point = new Number(8, 9);
Console.WriteLine(point.a);
Console.WriteLine(point.b);
}
}
struct Number
{
public int a;
public int b;
public Number(int a, int b)
{
this.a = a;
this.b = b;
}
}
C# Struct Examples:
Let us consider the classic example of storing students’ data. C# data structures are extensively used for such purposes where a certain list of information needs to be stored for a particular subject. The below example shows you how to do so and minimize code time significantly.
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace Struct
{
class Program
{
struct Student
{
public string FirstName;
public string Lastname;
public int RollNo;
public bool CompletedTest
}
static void Main(string[] args)
{
Student student1;
student1.FirstName = "Jane";
student1.Lastname = "Doe";
student1.RollNo = "9";
student1.CompletedTest = true;
}
}
}
C# Struct Vs. Class:
As mentioned earlier, C# structs are very similar to classes and function in a similar manner. However, there are salient differences that make both of these concepts unique. Let us look at some of these differences.
- The ‘struct’ keyword is used to declare a C# data structure, whereas, a ‘class’ keyword is used to declare a class.
- A class can have a default constructor without the presence of any parameters. This is not possible in C# struct constructors as a parameter is needed for it to function within structs.
- A class is of a reference data type, whereas, a struct is of a value data type. This means that when you pass a structure through a method, the actual structure is not passed but it is passed in the form of a value. A duplicate version of the value is present which is sent through the functions instead of the original structure. On the other hand, the function is passed on the original class itself since it is of a reference data type.
- Classes are stored on the heap, while on the other hand, structs are stored on the stack.
- Once the scope is lost, the value type data is destroyed immediately, but not the reference type data since they are destroyed later by the garbage collector.
These are some of the significant differences between a struct and a class in C#. And just like that, you now know enough about C# structs to get started with dealing with data structures. It may seem a little confusing in the beginning but with enough practical applications, anybody can get the hang of it. Structs are extensively used in data storage and retrieval, app developments, and game developments as well. Keep practicing and happy learning!
Do you know? |
---|
1. C# Enum |
2. C# Dictionary |
3. C# Switch Case |
4. C# Substring |
5. C# Foreach |
6. C# Struct |