1

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).

1
  • 2
    y does hold a value - you just assigned it indirectly. An integer type can only contain integer values never another int variable Commented Dec 1, 2017 at 1:41

2 Answers 2

1

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" 
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.