Search code examples
c#value-typereference-type

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


Solution

  • 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"