简体   繁体   中英

Would an int variable containing another int variable be considered a reference type?

I understand that value types hold values directly (int, bool, etc.), while reference types (such as classes) hold references to where the values are stored. I haven't yet found an answer to this specific question in other posts regarding reference and value types.

int x = 10;
int y = x;

// Would y be considered a reference type?

I ask this because while "int x" is a value type, "y" doesn't hold a value directly, it "references" to "x" (a different location in memory).

Would y be considered a reference type?

No.

Reference type vs. value type is a property of the type itself , not any of the variables of that type. Type int is a value type; therefore, all variables of type int are variables of a value type.

In your particular scenario, once y is assigned the value of x , it gets a copy of that value, not a reference to it. The values of x and y could be assigned independently of each other. If you subsequently change x , the value of y would remain unchanged:

int x = 10;
int y = x;
x = 5;
Console.WriteLine(y); // Prints 10

In contrast, variables of reference type "track" changes to the object that they reference:

StringBuilder x = new StringBuilder("Hello");
StringBuilder y = x;
x.Append(", world");
Console.WriteLine(y); // Prints "Hello, world"

I ask this because while "int x" is a value type, "y" doesn't hold a value directly, it "references" to "x" (a different location in memory).

y does not reference to x . For value types, the assignment (via the = operator) means to copy the value from the variable on the right side to the variable on the left side.

For reference types, it means to copy the reference .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM