A struct can bundle attributes together. If you create a struct, you can set a couple of variables for that struct. Those variables can be of any datatype.

A key difference from an array is that elements of an array are all of the same datatype. That is not the case with a struct.

If you want to combine variables, structs are the way to go. Unlike the concept of object oriented programming, they are just data holders.

Struct in c#

Struct example

The c# example creates a new struct. Then it sets the variables.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
using System;

struct Person {
public string job;
public string name;
};

public class testStructure {
public static void Main(string[] args) {
Person b;

b.name = "Bob";
b.job = "Chemist";

Console.WriteLine( "b.name : {0}", b.name);
Console.WriteLine("b.job : {0}", b.job);

Console.ReadKey();
}
}

The program bundles the variables (job, name) into a struct named Person.Then that structure can be used to set variables.

In this example the struct has only two variables, but a struct can have as many as you need.

You can create multiple items with the same struct, all with different values. Elements of a struct can be accessed immediately.

Exercises

  1. Create a struct house with variables noRooms, price and city
  2. How does a struct differ from a class?