Sobes.tech
Intern

What are the data types available in .NET?

sobes.tech AI

Answer from AI

In .NET, there are two main categories of data types:

Value Types:

  • Store their data directly on the stack or within the type itself.
  • When assigned or passed by value, a copy of the data is created.
  • Inherit from System.ValueType.
  • Examples:
    • Predefined value types:
      • Integer types: sbyte, byte, short, ushort, int, uint, long, ulong.
      • Floating-point types: float, double.
      • Decimal type: decimal.
      • Boolean type: bool.
      • Character type: char.
    • User-defined value types: struct, enum.

Reference Types:

  • Store a reference to data located in the heap.
  • When assigned or passed by value, only the reference is copied.
  • Inherit from System.Object.
  • Examples:
    • Predefined reference types:
      • String type: string.
      • Object type: object.
    • User-defined reference types: class, interface, delegate.
    • Arrays.
// Examples of value types
int age = 30; // Integer type
bool isActive = true; // Boolean type
char initial = 'J'; // Character type

// Struct declaration (user-defined value type)
struct Point
{
    public int X;
    public int Y;
}

// Examples of reference types
string name = "Alice"; // String type
object data = 123; // Object type

// Class declaration (user-defined reference type)
class Person
{
    public string Name { get; set; }
}

// Array declaration (reference type)
int[] numbers = { 1, 2, 3 };

Also, mention should be made of nullable value types, which allow value types to have a null value. They are declared with the ? suffix or Nullable<T> type.

int? optionalAge = null; // Nullable int
Nullable<DateTime> birthDate = new DateTime(2000, 1, 1); // Equivalent to DateTime?

Choosing between value types and reference types affects performance, memory management, and behavior during assignment and method passing.

What are the data types available in .NET? — C# - sobes.tech