404 Not Found

404 Not Found


nginx

Enums and Structs

Enums (enum)

An enum is a value type used to define a set of named constants, making code more readable and type-safe.

Defining an Enum

Use the enum keyword to define an enum. The default underlying type is int, starting from 0 and incrementing.

Example

CSHARP
enum Season
{
    Spring,
    Summer,
    Autumn,
    Winter
}

class Program
{
    static void Main()
    {
        Season current = Season.Autumn;
        System.Console.WriteLine(current);
        System.Console.WriteLine((int)current);
    }
}
▶ Try it Yourself
TEXT
Autumn
2

Underlying Type and Explicit Assignment

The underlying type of an enum defaults to int. You can explicitly specify another integer type and assign specific values to members.

Example

CSHARP
enum Priority : byte
{
    Low = 1,
    Medium = 2,
    High = 3
}

enum HttpStatusCode
{
    OK = 200,
    NotFound = 404,
    InternalServerError = 500
}

class Program
{
    static void Main()
    {
        Priority p = Priority.High;
        System.Console.WriteLine((byte)p);
        System.Console.WriteLine((int)HttpStatusCode.NotFound);
    }
}
▶ Try it Yourself
TEXT
3
404

Enum Conversion

Enums and their underlying types can be explicitly cast to each other.

Example

CSHARP
enum Season
{
    Spring,
    Summer,
    Autumn,
    Winter
}

class Program
{
    static void Main()
    {
        Season s = Season.Spring;
        int value = (int)s;
        System.Console.WriteLine(value);

        Season fromInt = (Season)2;
        System.Console.WriteLine(fromInt);
    }
}
▶ Try it Yourself
TEXT
0
Autumn

Enum Class Methods

The System.Enum class provides several static methods for enum operations.

Common Methods

Method Description
Enum.Parse Converts a string to an enum; throws an exception on failure
Enum.TryParse Converts a string to an enum; returns false on failure
Enum.GetName Gets the name of an enum value
Enum.GetValues Gets all enum values
Enum.IsDefined Determines whether a value is defined in the enum

Example

CSHARP
enum Season
{
    Spring,
    Summer,
    Autumn,
    Winter
}

class Program
{
    static void Main()
    {
        Season parsed = (Season)Enum.Parse(typeof(Season), "Summer");
        System.Console.WriteLine(parsed);

        bool ok = Enum.TryParse<Season>("Winter", out Season result);
        System.Console.WriteLine($"{ok}, {result}");

        string name = Enum.GetName(typeof(Season), 2);
        System.Console.WriteLine(name);

        foreach (Season s in Enum.GetValues(typeof(Season)))
        {
            System.Console.WriteLine($"{s} = {(int)s}");
        }

        System.Console.WriteLine(Enum.IsDefined(typeof(Season), 1));
        System.Console.WriteLine(Enum.IsDefined(typeof(Season), 99));
    }
}
▶ Try it Yourself
TEXT
Summer
True, Winter
Autumn
Spring = 0
Summer = 1
Autumn = 2
Winter = 3
True
False

Structs (struct)

A struct is a value type suitable for encapsulating small amounts of data. Structs are stored on the stack, and assignment copies the entire value.

Defining a Struct

Use the struct keyword to define a struct.

Example

CSHARP
struct Point
{
    public int X;
    public int Y;

    public Point(int x, int y)
    {
        X = x;
        Y = y;
    }

    public override string ToString()
    {
        return $"({X}, {Y})";
    }
}

class Program
{
    static void Main()
    {
        Point p1 = new Point(3, 4);
        Point p2 = p1;
        p2.X = 10;
        System.Console.WriteLine(p1);
        System.Console.WriteLine(p2);
    }
}
▶ Try it Yourself
TEXT
(3, 4)
(10, 4)

Struct vs Class

Structs and classes have important differences in semantics and behavior.

Comparison

Feature struct class
Type category Value type Reference type
Storage location Stack Heap
Assignment behavior Copies value Copies reference
Inheritance Not supported (cannot be inherited) Supported
Interfaces Can implement Can implement
Destructor None Yes
Default value All fields zero-valued null

Example

CSHARP
struct PointStruct
{
    public int X;
    public int Y;
}

class PointClass
{
    public int X;
    public int Y;
}

class Program
{
    static void Main()
    {
        PointStruct s1 = new PointStruct();
        PointStruct s2 = s1;
        s2.X = 5;
        System.Console.WriteLine($"struct: s1.X={s1.X}, s2.X={s2.X}");

        PointClass c1 = new PointClass();
        PointClass c2 = c1;
        c2.X = 5;
        System.Console.WriteLine($"class: c1.X={c1.X}, c2.X={c2.X}");
    }
}
▶ Try it Yourself
TEXT
struct: s1.X=0, s2.X=5
class: c1.X=5, c2.X=5

When to Use Structs

Structs are not always better than classes. Consider using a struct when:

Common examples: Point, Color, DateTime, TimeSpan.

⚠️ When the above conditions are not met, use a class to avoid performance degradation from frequent copying.

readonly struct (C# 7.2+)

readonly struct ensures all fields are immutable. The compiler prevents any modification operations.

Example

CSHARP
readonly struct Point
{
    public int X { get; }
    public int Y { get; }

    public Point(int x, int y)
    {
        X = x;
        Y = y;
    }

    public double DistanceTo(Point other)
    {
        int dx = X - other.X;
        int dy = Y - other.Y;
        return System.Math.Sqrt(dx * dx + dy * dy);
    }
}

class Program
{
    static void Main()
    {
        Point p1 = new Point(3, 4);
        Point p2 = new Point(0, 0);
        System.Console.WriteLine(p1.DistanceTo(p2));
    }
}
▶ Try it Yourself
TEXT
5

record struct (C# 10+)

record struct combines the value semantics of a struct with the value equality and concise syntax of a record, suitable for scenarios requiring immutability and auto-generated members.

Example

CSHARP
record struct Point(int X, int Y);

class Program
{
    static void Main()
    {
        Point p1 = new Point(1, 2);
        Point p2 = new Point(1, 2);
        System.Console.WriteLine(p1 == p2);
        System.Console.WriteLine(p1 with { X = 10 });
    }
}
▶ Try it Yourself
TEXT
True
Point { X = 10, Y = 2 }
💡 record struct auto-generates Equals, ToString, with expression, and other members, reducing boilerplate code.

❓ FAQ

Q Can an enum specify a non-integer type?
A No, only integer types can be specified (byte, sbyte, short, ushort, int, uint, long, ulong).
Q Can a struct have a constructor?
A Yes, it can have parameterized constructors, but the parameterless constructor is automatically provided by the compiler and cannot be custom-defined.
Q Can a struct implement interfaces?
A Yes, structs can implement interfaces. Boxing occurs when a struct is converted to an interface type (value-to-reference conversion).
Q Can readonly struct fields use set?
A No, all fields in a readonly struct must be readonly and can only be initialized through the constructor.
Q What is the difference between enum and const?
A An enum is a set of named constants with type safety; const is a single compile-time constant with no type grouping capability.

📖 Summary

📝 Exercises

  1. Define an enum Direction { North, East, South, West }, write code to iterate over all directions and output the name and integer value
  2. Define a struct Rectangle with width and height, provide a method to calculate area, and verify that assignment copies the value
  3. Change the Rectangle from the previous exercise to a readonly struct, ensuring all fields are read-only and initialized through the constructor
  4. Use Enum.TryParse and Enum.IsDefined to write a safe enum parsing method that takes a string and returns the corresponding enum value or a default value
  5. Write code to compare the behavioral difference between struct and class when passed as method parameters (value passing vs reference passing)
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏