search
HomeBackend DevelopmentC#.Net TutorialWhat is a constructor? What is the reference type?

Reference type
The constructor is a special method to initialize an instance of a type to a good state. When creating an instance of a reference type, memory is first allocated for the data fields of the instance, and then the additional fields of the object (type object pointer and synchronized block index), and finally calls the type's instance constructor to set the initialization state of the object.
When constructing a reference type object, the memory allocated for the object is always reset to 0 before the instance constructor of the electrophoresis type. All fields that are not explicitly overridden by the constructor are guaranteed to obtain 0 or null values. .
Unlike other methods, the strength constructor can never be inherited, that is to say, the class only has the smooth constructor defined by the class itself. Since an instance constructor can never be inherited, the following modifiers cannot be used on an instance constructor: Virtual, new, override, sealed, and abstract. If the class does not explicitly define any constructor, the C# compiler will default to a default parameterless constructor. In her implementation, it simply calls the parameterless constructor of the base class.
If the class modifier is abstract, the accessibility of the default constructor generated by the compiler is product; otherwise, the constructor will be assigned the public accessible attribute. If the base class does not provide a parameterless constructor, the derived class must explicitly call a base class constructor, otherwise the compiler will report an error. If the class modifier is static (sealed and abstract), the compiler will not generate a default constructor in the class definition at all.
A type can define multiple instance constructors. Each constructor must have a different signature, and each can have different accessible properties. In order to make the code "verifiable", the class's initializer must call the base class's constructor before accessing any fields inherited from the base class. If the derived class constructor does not explicitly call a base class constructor, the C# compiler will automatically generate a call to the default base class constructor. Eventually, System.Object's public no-argument constructor will be called. The constructor does nothing and returns directly. Since System.Object has no instance data fields, its constructor has nothing to do.
In rare cases it is possible to create a type instance without calling the instance constructor. A typical example is the MemberwiseClone method of Object. What this method does is allocate memory, initialize the object's additional fields, and then copy the source object's own data into the new object. In addition, when deserializing an object using a runtime serializer, the same process does not need to call the constructor. Deserialization uses the GetUnnitalizedObject or GetSafeUninitailizedObject method of the System.Runtime.Serialization.FormatterServices type to allocate memory for the object, and a constructor will not be called during the process.
Tips:
Do not call virtual methods in the constructor. The reason is that if the instantiated type overrides the virtual method, the derived type's implementation of the virtual method will be executed, but at this time, the initialization of all fields in the inheritance hierarchy has not been completed (the constructor of the instantiated type not running yet). Therefore, calling virtual methods can lead to unpredictable behavior. Ultimately, this is because when a virtual method is called, the actual type on which the method is executed is not selected until runtime.
Value type (struct) constructor
The value type (struct) constructor works completely differently from the constructor of the reference type (class). The CLR always allows the creation of instances of value types, and there is no way to prevent the instantiation of value types. Therefore, value types do not actually need to define a constructor, and the C# compiler will not inline a default no-argument constructor for value types at all. Let’s look at the following code:
internal struct Point {
public int m_x, m_y;
}
internal sealed class Reactangel
{
public Point m_TopLeft, m_bottomRight;
}
In order to construct a Rectangle, the new operator must be used and the constructor must be specified. In this example, the default constructor automatically generated by the C# compiler is called. Allocate memory for Reatangle, which contains two instances of the Point value type. Considering performance, the CLR will not actively call the constructor for each value type field contained in the reference type. However, as mentioned above, the value type fields will be initialized to 0 or null.
The CLR does allow constructors to be defined for value types, but they must be explicitly called before they are executed.
internal struct Point {
public int m_x, m_y;
public Point(int x, int y)
{
m_x = x;
m_y = y;
}
}
internal sealed class Reactangel
{
public Point m_TopLeft, m_bottomRight;
public Reactangel()
{
this.m_TopLeft = new Point(1 ,2);
this.m_bottomRight = new Point(100,200);
}
}
Instance constructors of value types will only be executed when explicitly called. Therefore, if the constructor of Rectangle does not use the new operator to call the constructor of Point to initialize the m_TopLeft and m_bottomRight fields of Reatangle, then the m_x and m_y fields in both point fields will be 0.
Rewrite the above code:
internal struct Point {
public int m_x, m_y;
public Point()
{
m_x = 5;
m_y = 6;
}
}
internal sealed class Reactangel
{
public Point m_TopLeft, m_bottomRight;
public Reactangel()
{
}
}
Now, when constructing a new Rectangle class, how much will the m_x and m_y fields in the two Point fields be initialized? Is it 0 or 5?
You may think that the C# compiler will generate code in Reactangel's constructor and automatically call Point's default parameterless constructor for Reactangel's two fields. However, to enhance the runtime performance of your application, the C# compiler does not automatically generate such code. In fact, even if a value type provides a parameterless constructor, many compilers will never generate code to call it. In order to implement a value type parameterless constructor, the developer must add code that explicitly calls the value type constructor. But will the two fields of Point' be initialized to 0 for this reason? The result is:
The C# compiler deliberately does not allow value types to define parameterless constructors in order to prevent Developers are confused about when this constructor is called. Since a parameterless constructor cannot be defined, the compiler will never generate code that automatically calls it. Without a parameterless constructor, fields of value types are always initialized to 0 or null.
Type constructor:
Also known as static constructor, class constructor or type initializer. Type constructors can be used with reference types and value types. The purpose of an instance constructor is to set the initial state of an instance of a type. Correspondingly, the role of the type constructor is to set the initial state of the type. The type does not define a type constructor by default. If it is defined, there can only be one. Furthermore, type constructors never have parameters.
internal sealed class SomeRefType {
static SomeRefType()
{
//When accessing for the first time, execute the code here
}
}
internal struct SomeValType
{
static SomeValType()
{
//When accessing for the first time, execute the code here
}
}
It can be seen that defining a type constructor is similar to defining a parameterless instance constructor. The difference is that it must be marked static. Furthermore, type constructors are always private. The reason why it is private is to prevent any developer from writing code to call it, and the CLR is always responsible for his calls.
Tips:
Although you can define a type constructor in a value type, you should never actually do it because the CLR sometimes does not call the static constructor of the value type: for example
internal struct SomeValType
{
static SomeValType()
{
Console.WriteLine("This sentence will never be displayed") ;
}
public int m_x;
}
class Program
{
static void Main( string[] args)
{
SomeValType[] a = new SomeValType[10];
a[0].m_x = 123;
Console.WriteLine(a[0].m_x);
Console.ReadKey();
}
}
The code of the type constructor only Can access the static fields of the type, and its unconventional use is to initialize these fields.

The above is the detailed content of What is a constructor? What is the reference type?. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Deploying C# .NET Applications to Azure/AWS: A Step-by-Step GuideDeploying C# .NET Applications to Azure/AWS: A Step-by-Step GuideApr 23, 2025 am 12:06 AM

How to deploy a C# .NET app to Azure or AWS? The answer is to use AzureAppService and AWSElasticBeanstalk. 1. On Azure, automate deployment using AzureAppService and AzurePipelines. 2. On AWS, use Amazon ElasticBeanstalk and AWSLambda to implement deployment and serverless compute.

C# .NET: An Introduction to the Powerful Programming LanguageC# .NET: An Introduction to the Powerful Programming LanguageApr 22, 2025 am 12:04 AM

The combination of C# and .NET provides developers with a powerful programming environment. 1) C# supports polymorphism and asynchronous programming, 2) .NET provides cross-platform capabilities and concurrent processing mechanisms, which makes them widely used in desktop, web and mobile application development.

.NET Framework vs. C#: Decoding the Terminology.NET Framework vs. C#: Decoding the TerminologyApr 21, 2025 am 12:05 AM

.NETFramework is a software framework, and C# is a programming language. 1..NETFramework provides libraries and services, supporting desktop, web and mobile application development. 2.C# is designed for .NETFramework and supports modern programming functions. 3..NETFramework manages code execution through CLR, and the C# code is compiled into IL and runs by CLR. 4. Use .NETFramework to quickly develop applications, and C# provides advanced functions such as LINQ. 5. Common errors include type conversion and asynchronous programming deadlocks. VisualStudio tools are required for debugging.

Demystifying C# .NET: An Overview for BeginnersDemystifying C# .NET: An Overview for BeginnersApr 20, 2025 am 12:11 AM

C# is a modern, object-oriented programming language developed by Microsoft, and .NET is a development framework provided by Microsoft. C# combines the performance of C and the simplicity of Java, and is suitable for building various applications. The .NET framework supports multiple languages, provides garbage collection mechanisms, and simplifies memory management.

C# and the .NET Runtime: How They Work TogetherC# and the .NET Runtime: How They Work TogetherApr 19, 2025 am 12:04 AM

C# and .NET runtime work closely together to empower developers to efficient, powerful and cross-platform development capabilities. 1) C# is a type-safe and object-oriented programming language designed to integrate seamlessly with the .NET framework. 2) The .NET runtime manages the execution of C# code, provides garbage collection, type safety and other services, and ensures efficient and cross-platform operation.

C# .NET Development: A Beginner's Guide to Getting StartedC# .NET Development: A Beginner's Guide to Getting StartedApr 18, 2025 am 12:17 AM

To start C#.NET development, you need to: 1. Understand the basic knowledge of C# and the core concepts of the .NET framework; 2. Master the basic concepts of variables, data types, control structures, functions and classes; 3. Learn advanced features of C#, such as LINQ and asynchronous programming; 4. Be familiar with debugging techniques and performance optimization methods for common errors. With these steps, you can gradually penetrate the world of C#.NET and write efficient applications.

C# and .NET: Understanding the Relationship Between the TwoC# and .NET: Understanding the Relationship Between the TwoApr 17, 2025 am 12:07 AM

The relationship between C# and .NET is inseparable, but they are not the same thing. C# is a programming language, while .NET is a development platform. C# is used to write code, compile into .NET's intermediate language (IL), and executed by the .NET runtime (CLR).

The Continued Relevance of C# .NET: A Look at Current UsageThe Continued Relevance of C# .NET: A Look at Current UsageApr 16, 2025 am 12:07 AM

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function