Summary of the difference between Struct and Class in C#

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 classa 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 newinstantiating 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.ValueTypeand inherited from it System.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 members protected, or protected internalmodifiers.

  • Function member structural body can not be abstract ( abstract) or virtual ( virtual), rewriting ( override) only allows rewriting modifier from System.ValueTypeinherited 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>in T), its assigned nullvalue, 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 stackallocated on the stack ( ), or allocated inline in the containing type. The class is a reference type, heapallocated 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 ( refand outexcept 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, doubleand 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 stackallocated 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 heapallocated 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.Equalsthe 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.ValueTypeThe Equalsuse of reflection to achieve, because it must be able to determine which fields have any structure. When you create your own structure, rewrite Equalsmethod may provide information specific to your type of efficient algorithms seek.

"Value-based equality" is recordsimilar 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

Public Number: Technical Translation Station

Guess you like

Origin blog.csdn.net/weixin_47498376/article/details/108782711