Analysis on some problems of c# struct

Time:2021-11-30
catalogue
  • Difference from class:

Struct’s theory has been read better, but it has not been applied in work. Class exists everywhere. Doesn’t struct have any use value? Searched how to choose between classes and structures?

✔️ If the instance of a type is small and usually has a short lifetime or is usually embedded in other objects, consider defining a structure rather than a class.

❌ Avoid defining structures unless the type has all of the following characteristics:

It logically represents a single value, similar to the original type (int, double, etc.).

Its instance size is less than 16 bytes.

It is immutable.

It doesn’t have to be boxed often.

When developing software, there are often page pop-up windows, and the main page often needs to pass some parameters to the form. The form only uses these parameters to find other data display or save data, that is, read-only those input parameters. Although multiple parameters can be passed through the constructor, it is generally better to encapsulate multiple parameters as a whole. If these parameters can be regarded as a small logical unit in business, it should be better to encapsulate them into struct.

Eg: when the function passes parameters, struct will be copied again, so add Ref.

using System;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        private FundStruct s_fundStruct;

        public Form1()
        {
            InitializeComponent();
        }
      
        public Form1(ref FundStruct fundStruct)
        {
            InitializeComponent();
            s_fundStruct = fundStruct;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.textBox1.Text = s_fundStruct.Code;
            this.textBox2.Text = s_fundStruct.ShortName;
            ...
        }
    }

    public struct FundStruct
    {
        /// <summary>
        ///Code
        /// </summary>
        internal readonly string Code;
        /// <summary>
        ///Internal code number
        /// </summary>
        internal readonly int Number;
        /// <summary>
        ///Abbreviation
        /// </summary>
        internal readonly string ShortName;
        /// <summary>
        ///Full name
        /// </summary>
        internal readonly string LongName;

        internal FundStruct(string code, int number, string shortName, string longName)
        {
            Code = code ?? throw new ArgumentNullException(nameof(code));
            Number = number;
            ShortName = shortName ?? throw new ArgumentNullException(nameof(shortName));
            LongName = longName ?? throw new ArgumentNullException(nameof(longName));
        }
    }
}

Difference from class:

Structure types and class types in C # are very similar in syntax. They are both data structures and can include data members and method members.

Differences between structure and class:

1. Structure is a value type, which allocates space in the stack; Class is a reference type, which allocates space in the heap, and only references are saved in the stack.
2. The structure type directly stores the member data, so that the data of other classes are located in the heap. The variables located in the stack store references to the data objects in the heap.

Simple types in C # such as int, double, bool, etc. are all structural types. If necessary, you can even use structure type combined with operator operation overload, and then create a new value type for c# language.

Because the structure is a value type and stores data directly, using the structure will bring better performance when the main member of an object is data and the amount of data is small.

Because structures are value types, they perform very well when allocating memory for structures or when structures are deleted out of scope because they are inlined or saved on the stack. When a variable of one structure type is assigned to another structure, the impact on performance depends on the size of the structure. If the data members of the structure are very large and complex, it will cause losses. Next, a piece of code is used to illustrate this problem.

Application analysis of structure and class:

1. When the stack space is limited and there are a large number of logical objects, it is better to create classes than structures;
2. For lightweight objects such as point, rectangle and color, if you want to declare an array containing many color objects, CLR needs to allocate memory for each object. In this case, the cost of using structure is low;
3. When representing abstract and multi-level object hierarchies, classes are the best choice because structures do not support inheritance.
4. In most cases, the target type only contains some data or is dominated by data.

The above is the details of some problem analysis of c# struct. For more information about c# struct, please pay attention to other relevant articles of developeppaer!