C# struct
The struct keyword defines a structure in C#. A structure is a value type that can group related fields, properties, methods, constructors, operators, events, and nested types into a single type.
Structures are commonly used for small data values that have value semantics, such as coordinates, dimensions, dates, colors, measurements, and other data that represents one logical value.
Syntax of C# struct
Following is the syntax of structure in C# programming language.
struct StructureName {
/* properties (constants/fields) */
/* methods */
/* nested types */
}
where
- struct is the keyword
- StructureName is the name by which we access the C# Structure.
A structure can contain properties that are constants or fields, methods, nested types.
By convention, C# structure names use PascalCase, such as StudentRecord, Point, or Temperature.
Example C# Structure
Following is an example structure in C#. This is a struct named Student, contains properties Name, Age; method printStudentDetails() to print the details of student and a constructor to assign the values to the object of this struct Student type.
Program.cs
using System;
namespace CSharpExamples {
struct Student{
//properties
string Name;
int Age;
//constructor
public Student(string name, int age){
Name = name;
Age = age;
}
//methods
public void printStudentDetails(){
Console.WriteLine("Name : "+Name);
Console.WriteLine("Age : "+Age);
}
}
class Program {
static void Main(string[] args) {
Student s1 = new Student("Lini", 27);
s1.printStudentDetails();
}
}
}
Output
PS D:\workspace\csharp\HelloWorld> dotnet run
Name : Lini
Age : 27
The constructor initializes the two fields when the Student value is created. The printStudentDetails() method then reads those fields and writes them to the console.
Creating and Accessing a C# struct Value
A structure value can be created by calling one of its constructors. Its accessible fields, properties, and methods can then be used with the member-access operator.
using System;
struct Point
{
public int X { get; set; }
public int Y { get; set; }
public Point(int x, int y)
{
X = x;
Y = y;
}
public void Print()
{
Console.WriteLine($"({X}, {Y})");
}
}
class Program
{
static void Main()
{
Point location = new Point(12, 8);
Console.WriteLine(location.X);
Console.WriteLine(location.Y);
location.Print();
}
}
Output
12
8
(12, 8)
Default Values of C# struct Members
Every structure has a default value. When a structure is initialized with default or with a parameterless object-creation expression, its fields initially contain the default values of their respective types.
using System;
struct ProductStock
{
public int Quantity;
public bool IsAvailable;
}
class Program
{
static void Main()
{
ProductStock stock = default;
Console.WriteLine(stock.Quantity);
Console.WriteLine(stock.IsAvailable);
}
}
Output
0
False
In this example, the default value of int is 0, and the default value of bool is false.
C# struct Uses Value-Type Copying
A structure is a value type. Assigning one structure variable to another normally copies its current data. After the assignment, changing one copy does not change the other copy.
using System;
struct Score
{
public int Points;
}
class Program
{
static void Main()
{
Score first = new Score { Points = 75 };
Score second = first;
second.Points = 90;
Console.WriteLine(first.Points);
Console.WriteLine(second.Points);
}
}
Output
75
90
The assignment copies the value of first into second. The two variables can then be changed independently.
Passing a C# struct to a Method
When a structure is passed to a method by value, the method receives a copy. Changes made to that parameter do not affect the original variable.
using System;
struct Counter
{
public int Value;
}
class Program
{
static void Increment(Counter counter)
{
counter.Value++;
}
static void Main()
{
Counter counter = new Counter { Value = 10 };
Increment(counter);
Console.WriteLine(counter.Value);
}
}
Output
10
To let the method update the original structure variable, pass it by reference with ref.
using System;
struct Counter
{
public int Value;
}
class Program
{
static void Increment(ref Counter counter)
{
counter.Value++;
}
static void Main()
{
Counter counter = new Counter { Value = 10 };
Increment(ref counter);
Console.WriteLine(counter.Value);
}
}
Output
11
Readonly struct for Immutable C# Values
A readonly struct is intended to represent a value whose instance state does not change after construction. Its instance fields must be readonly, and properties that store state should normally expose getters without mutable setters.
using System;
readonly struct Temperature
{
public double Celsius { get; }
public Temperature(double celsius)
{
Celsius = celsius;
}
public double ToFahrenheit()
{
return (Celsius * 9 / 5) + 32;
}
}
class Program
{
static void Main()
{
Temperature temperature = new Temperature(25);
Console.WriteLine(temperature.Celsius);
Console.WriteLine(temperature.ToFahrenheit());
}
}
Output
25
77
Readonly structures are useful when a value should remain consistent after it has been created.
C# record struct for Value-Based Data Models
A record struct combines value-type behavior with generated record members, including value-based equality and a readable string representation. It is useful for compact data models where two values with the same component values should compare as equal.
using System;
public readonly record struct Coordinate(int X, int Y);
class Program
{
static void Main()
{
Coordinate first = new Coordinate(4, 7);
Coordinate second = new Coordinate(4, 7);
Console.WriteLine(first);
Console.WriteLine(first == second);
}
}
Output
Coordinate { X = 4, Y = 7 }
True
Implementing an Interface with a C# struct
A structure cannot inherit from a user-defined class or another structure, but it can implement one or more interfaces.
using System;
interface IPrintable
{
void Print();
}
struct InvoiceNumber : IPrintable
{
public int Value { get; }
public InvoiceNumber(int value)
{
Value = value;
}
public void Print()
{
Console.WriteLine($"Invoice: {Value}");
}
}
class Program
{
static void Main()
{
InvoiceNumber invoice = new InvoiceNumber(1042);
invoice.Print();
}
}
Output
Invoice: 1042
Difference between Class and Structure in C#
Now that we have come across class and structure in C#, you may be wondering, what is the difference between these two types: class and structure.
Well! The basic difference is that a class of reference type while structure is of value type.
| Feature | C# struct | C# class |
|---|---|---|
| Type category | Value type | Reference type |
| Assignment behavior | Normally copies the value | Copies the object reference |
| Null by default | No, unless used as a nullable value type | Yes, a class variable can contain null |
| Inheritance | Cannot inherit from another class or struct | Can inherit from another class |
| Interface implementation | Supported | Supported |
| Best suited for | Small values with value semantics | Objects with identity, shared state, or inheritance |
Use a structure when the type represents one compact value and copying that value is meaningful. Use a class when instances need independent identity, shared references, inheritance, or substantial mutable state.
When to Use a C# struct
A structure is generally a suitable choice when the type has most of the following characteristics:
- It represents one logical value rather than an object with identity.
- It is relatively small.
- Its values are immutable or changed infrequently.
- Copying the entire value is expected and understandable.
- It does not need class inheritance.
Examples include a two-dimensional point, a range, a date component, a measurement, or a pair of related numeric values.
When a C# class Is Better Than a struct
A class is usually more appropriate when the type is large, frequently mutated, shared across several parts of a program, or expected to participate in an inheritance hierarchy.
Large mutable structures can be harder to reason about because assignment and method calls may create copies. Copying a large structure repeatedly can also add unnecessary work.
Common C# struct Mistakes
- Assuming two struct variables refer to the same instance after assignment.
- Using a large mutable struct when a class would make shared-state behavior clearer.
- Forgetting that passing a struct to a method by value creates a copy.
- Expecting a struct to inherit from a custom class.
- Mutating a struct returned from a property without assigning the updated value back.
- Using public mutable fields when properties or an immutable design would be clearer.
C# struct Editorial QA Checklist
- Verify that the tutorial describes a struct as a value type.
- Confirm that assignment and parameter-passing examples explain copying correctly.
- Check that all struct constructors initialize the required instance state.
- Confirm that inheritance claims distinguish class inheritance from interface implementation.
- Use
readonly structwhen the sample is intended to be immutable. - Recommend a class instead when the example requires identity, shared mutable state, or inheritance.
Frequently Asked Questions About C# struct
Is a C# struct a value type?
Yes. A C# structure is a value type. Assigning it to another variable normally copies its value rather than creating another reference to the same object.
Can a C# struct have a constructor?
Yes. A structure can define constructors to initialize its members. It also always has a default value in which its fields contain their type-specific default values.
Can a C# struct inherit from a class?
No. A structure cannot inherit from a user-defined class or another structure. It can, however, implement interfaces.
Can a C# struct be null?
A non-nullable structure variable cannot contain null. To allow a structure value to be absent, use a nullable value type such as Point? or Nullable<Point>.
Should a C# struct be immutable?
It is often a good design choice. Immutable structures avoid unexpected changes to copied values and are easier to use safely. The readonly struct declaration can enforce an immutable instance-state design.
Summary of C# struct Usage
A C# struct defines a value type that can contain fields, properties, methods, constructors, and nested types. Structure assignment normally copies data, and passing a structure by value gives a method a copy. Structures are most suitable for small values with clear value semantics, while classes are generally better for shared, mutable, inherited, or identity-based objects.
TutorialKart.com