Object

JunDev·2025년 3월 4일

C#

목록 보기
16/23

Value and Reference Types

  • (value type) stores its own value directly in memory.
  • (reference type) can hold a reference to an object on the heap.
  • Value types (int, float, bool) store data directly on the stack.
  • Reference types (object, class, string, array) store a reference to an object on the heap.
  • Boxing (int → object) creates a copy on the heap, so changes to the original value type don’t affect the boxed object.
// value/ref types
int valueType = 10;
object referenceType = valueType; // specifically refers to the "valueType" variable that appears before itself

valueType = 20;

Console.WriteLine($"ValueType: {valueType}"); // 20
Console.WriteLine($"ReferenceType: {referenceType}"); // 10
// boxing (converts var into ref and vice-versa, changes to the original is not affected)
int value = 42;
object boxed = value; // boxing
int unboxed = (int)boxed; // unboxing

Console.WriteLine($"Boxed: {boxed}, Unboxed: {unboxed}"); // Boxed: 42, Unboxed: 42

is/as

The is keyword is used to check if an object is of a specific type or can be cast to that type. It returns a boolean value (true or false).

// is
object obj = "Hello";

Console.WriteLine(obj is string); // true
Console.WriteLine(obj is int); // false

The as keyword is used for casting an object to a specific type, but it returns null if the cast is not possible, instead of throwing an exception like a traditional cast would.

// as
object obj = "Hello";
string str = obj as string;

Console.WriteLine(str is string); // true

profile
Jun's Dev Journey

0개의 댓글