Translated from Manju lata Yadav's blog post "Difference Between Struct And Class In C#" on June 2, 2019, with some content and examples added.
The structure ( struct
) is class
a lightweight version of the class ( ). Structures are value types and can be used to create objects that behave like built-in types.
Compare
Structures and classes share many characteristics, but they have the following limitations compared to classes.
-
The structure cannot have a default constructor (parameterless constructor) or destructor, and all fields must be assigned values in the constructor.
public struct Coords { public double x; public double y; public Coords() //错误,不允许无参构造函数 { this.x = 3; this.y = 4; } public Coords(double x) //错误,构造函数中必须给所有字段赋值 { this.x = x; } public Coords(double x) //这个是正确的 { this.x = x; this.y = 4; } public Coords(double x, double y) //这个是正确的 { this.x = x; this.y = y; } }
-
The structure is a value type and is copied when assigning a value.
-
Structures are value types, and classes are reference types.
-
Structure can be used without
new
instantiating case operator.
E.g:public struct Coords { public double x; public double y; } static void Main() { Coords p; p.x = 3; p.y = 4; Console.WriteLine($"({p.x}, {p.y})"); // 输出: (3, 4) }
-
A structure cannot inherit from another structure or class, and a class cannot inherit a structure. All structures are directly inherited from the abstract class
System.ValueType
,System.ValueType
and inherited from itSystem.Object
. -
Structure is the base class can not, therefore, is not the structure
abstract
, and the seal is always implicit (sealed
). -
Abstract is not allowed (for the structure
abstract
) and the seal (sealed
) modifier is not allowed use of the structure membersprotected
, orprotected internal
modifiers. -
Function member structural body can not be abstract (
abstract
) or virtual (virtual
), rewriting (override
) only allows rewriting modifier fromSystem.ValueType
inherited methods. -
Instance attributes or fields are not allowed to contain initializers in the structure. However, the structure allows static properties or fields to contain initializers.
E.g:public struct Coords { public double x = 4; //错误, 结构体中初始化器不允许实例字段设定初始值 public static double y = 5; // 正确 public static double z { get; set; } = 6; // 正确 }
-
Structures can implement interfaces.
-
Structure may be used
nullable type
(ie:Nullable<T>
inT
), its assignednull
value, reference [Nullable<T> Struct
]
When to use a structure or class?
To answer this question, we should understand their differences well.
Serial number | Structure ( struct ) |
Class( class ) |
---|---|---|
1 | The structure is a value type and can be stack allocated on the stack ( ), or allocated inline in the containing type. |
The class is a reference type, heap allocated on the heap ( ) and garbage collected. |
2 | The allocation and release of value types are usually more cost-effective than the allocation and release of reference types. | Assignment of large reference types is cheaper than assignment of large value types. |
3 | In the structure, each variable contains its own copy of the data ( ref and out except for parameter variables), the operation of a variable does not affect the other. |
In a class, two variables can contain references to the same object, and any operation on one variable will affect the other variable. |
In this way, the structure ( struct
) can only be used in the following situations:
- It represents a single value, such as the type of base (logically
int
,double
and the like). - It is immutable.
- It will not be boxed and unboxed frequently.
In all other cases, the type should be defined as a class ( class
).
Structure example:
struct Location
{
public int x, y;
public Location(int x, int y)
{
this.x = x;
this.y = y;
}
}
static void Main()
{
Location a = new Location(20, 20);
Location b = a;
a.x = 100;
Console.WriteLine(b.x);
}
The output will be 20. The value of "b" is a copy of "a", so "b" is not affected by the change of "ax". But in the class, the output will be 100 because the variables "a" and "b" refer to the same object.
The following is the translator's supplement
Structure instance and class instance
The memory of the structure instance is stack
allocated on the stack ( ), and the occupied memory is reclaimed along with the type or method in which it is declared. This is one reason to copy the structure when assigning. In contrast, the memory of a class instance is heap
allocated on the heap ( ). When all references to the class instance are out of range, the memory allocated for the class instance will be automatically reclaimed by the common language runtime (garbage collection).
Value equality of structure instances
The comparison of two structure instances is based on the comparison of values, while the comparison of class instances is the comparison of their references.
To determine the two bodies of Examples example structure field has the same value, use ValueType.Equals
the method. Since all structures are implicitly inherited from System.ValueType
, this method can be called directly on its object, as shown in the following example:
public struct Person
{
public string Name;
public int Age;
public Person(string name, int age)
{
Name = name;
Age = age;
}
}
static void Main()
{
Person p1 = new Person("技术译站", 100);
Person p2;
p2.Name = "技术译站";
p2.Age = 100;
if (p2.Equals(p1))
Console.WriteLine("p2 和 p1 有相同的值。");
Console.ReadKey();
}
// 输出: p2 和 p1 有相同的值。
System.ValueType
The Equals
use of reflection to achieve, because it must be able to determine which fields have any structure. When you create your own structure, rewrite Equals
method may provide information specific to your type of efficient algorithms seek.
"Value-based equality" is record
similar to the new record ( ) type in C# 9.0. If you want to know C# 9.0, you can check: Welcome to C# 9.0 .
Author: Manju lata Yadav
Translator: Technical Zemin
Publisher: Technical Verses
links: English text