C# struct also known as C# structure is a simple user-defined type, a lightweight alternative to a class. A stuct in C# is simply a composite data type consisting of a number elements of other types. This article and code examples implements C# Structs.
Similar to classes, structures have behaviors and attributes. As a value type, structures directly contain their value so their object or instance is stored on the stack.
C# Struts support access modifiers, constructors, indexers, methods, fields, nested types, operators, and properties.
How to define a struct in C#
- public struct Student {
- int id;
- int zipcode;
- double salary;
- }
Note: Struct members may not be declared protected.
Structs are simple to use and can prove to be useful at times. Just keep in mind that they're created on the stack and that you're not dealing with references to them but dealing directly with them. Whenever you have a need for a type that will be used often and is mostly just a piece of data, structs might be a good option.
How to use a struct in C#
- using System;
- namespace example_struct {
- class Program {
- public struct Student {
- int id;
- int zipcode;
- double salary;
- // all the members of the struct has to be initialized in this way
- public Student(int id, int zipcode, double salary) {
- this.id = id;
- this.zipcode = zipcode;
- this.salary = salary;
- }
- // all the members of the struct has to be initialized either in this way
- public Student(int id, int zipcode) {
- this.id = id;
- this.zipcode = zipcode;
- this.salary = 3400.00;
- }
- // if you left any member of a struct uninitialzed it will give error
- // code below will give error because the zipcode and salary field is left uninitialzed
- //public Student(int id)
- //{
- // this.id = id;
- //}
- // struct can also have copy constructor but have to be fully initialzed
- public Student(Student x) {
- this.id = x.id;
- this.zipcode = x.zipcode;
- this.salary = x.salary;
- }
- public void DisplayValues() {
- Console.WriteLine("ID: " + this.id.ToString());
- Console.WriteLine("Zipcode : " + this.zipcode.ToString());
- Console.WriteLine("Salary : " + this.salary.ToString());
- }
- }
- static void Main(string[] args) {
- Student stu = new Student(12, 201301, 4560.00);
- Student stu1 = new Student(stu);
- stu.DisplayValues();
- Console.WriteLine("Copy constructor values");
- stu1.DisplayValues();
- Console.ReadLine();
- }
- }
- }

Join the conversation! Your thoughts help the community grow.