Sobes.tech
Junior — Middle

Can you list the main features of data types in C# and their differences?

sobes.tech AI

Answer from AI

In C#, the main data types are divided into two categories: value types and reference types.

  • Value types store data directly in the memory where they are declared. They include primitive types such as int, double, bool, as well as structures (struct). When assigned, the value is copied.

  • Reference types store a reference to an object in managed heap. They include classes (class), arrays, strings (string), delegates. When assigned, the reference is copied, not the object itself.

Differences:

  • Value types are usually faster and occupy less memory but have limitations in functionality.
  • Reference types allow creating complex data structures and support inheritance.

Example:

int a = 5;
int b = a; // value is copied
b = 10;
// a remains 5

class Person { public string Name; }
Person p1 = new Person { Name = "Alice" };
Person p2 = p1; // reference is copied
p2.Name = "Bob";
// p1.Name is now "Bob"