Home >Backend Development >C++ >Reference vs. Value Types in C#: What's the Difference?

Reference vs. Value Types in C#: What's the Difference?

Susan Sarandon
Susan SarandonOriginal
2025-02-02 10:01:09852browse

Reference vs. Value Types in C#: What's the Difference?

In -depth understanding of the reference type and value type in C#

C# programming, understanding the difference between reference type and value type is very important. Although both of them store data, their behavior and usage are very different.

Quote type

C# quotation types are non -basic types, such as interfaces, commission, and even customized classes. They hold references to type instances, not the actual value itself. This means that two variables of the same reference type can point to the same underlying object.

Value type

On the other hand, the value type, such as integer, Boolean value, and floating -point numbers, directly store their values. When the value type variable is assigned to another variable, a complete copy will be created. The change of one variable will not affect the other variable. Main differences

The main difference between the quotation type and value type in the table below:

Actual examples

Consider the following code:
特性 引用类型 值类型
内存地址 实际数据
复制行为 仅复制引用 复制整个值
赋值 分配不同的地址 分配相同的值
标识 对象可以共享标识 对象具有唯一标识
空值 可以为空 不能为空(可空类型除外)

In this example, Number1 is a value type, so the copy of the value is assigned to Number2. Modifying Number1 does not affect Number2 because they are two independent variables with each self -value.

Now, let's take a look at an example of reference type:

<code class="language-csharp">int number1 = 5;
int number2 = number1;

// 修改 number1
number1++;

// number2 保持不变
Console.WriteLine(number2); // 输出:5</code>
In this case, Person is a reference type, so Person1 and Person2 point to the same object. Modifying Person1 will change the underlying object, which will be reflected in Person1 and Person2.

The above is the detailed content of Reference vs. Value Types in C#: What's the Difference?. 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