Subscribe
Home » Learn How to Use Structures in C#

Learn How to Use Structures in C#

by Staff
0 comment

C#’s structs are like a lightweight, but powerful, alternative to classes. Find out how to use this handy data type.

In C#, the two main type categories are value types (such as structures), and reference types (such as classes). Because a structure (or struct) is a value type it is data-centric.

A struct can store attributes and related methods that, preferably, do not focus on behavior.

How to Declare a Struct

Each struct declaration must have the struct keyword. Precede the struct keyword with an access modifier and include a name and a pair of curly braces after it. Here’s how to declare a struct called Game:

    public struct Game {}

How to Populate a Struct

A struct stores data within its curly braces, in the form of attributes, constructors, methods, events, etc.

public struct Game
{
public string name;
public string description;
public int levels;

public Game (string name, string description, int levels) {
this.name = name;
this.description = description;
this.levels = levels;
}

public override string ToString() => $"Name: {name}, Description: {description}, Levels: {levels}";
}

The Game struct now has three attributes, a constructor, and a method. These are three primary components of a C# struct, which are also three of the primary components of a C# class.

How to Create a Struct Variable

Each instance of a C# struct is known as a variable. There are two ways to create a variable from a struct. You can use a constructor:

Game game1 = new Game("Pokémon GO", "Lorem ipsum dolor sit amet.", 50);

Or you can assign values to individual attributes of a struct using the dot (.) operator:

Game game1;
game1.name = "Pokémon GO";
game1.description = "Lorem ipsum dolor sit amet.";
game1.levels = 50;

Both approaches achieve the same result. The code above uses C# to develop a game object called Pokémon GO that has a brief description and 50 levels. So, now you can use the game1 object.

Console.WriteLine(game1.ToString());

This prints the following output to the console:

Name: Pokémon GO, Description: Lorem ipsum dolor sit amet., Levels: 50

The Differences Between a Struct and a Class

A struct and a class have a similar appearance, but they have many notable differences. They use different keywords for declaration. And structs support neither null references nor inheritance.

Read the full article here

You may also like

Leave a Comment

Iman Hearts is one of the biggest lifestyle news and articles portals, we provide the latest news and articles about family, lifestyle, entertainment, and many more, follow us to get the latest news about what matters to you.

 

2022 © Iman Hearts, All Right Reserved.