C# Classes, Properties, and Records
Introduction
C# is an object-oriented language: you describe things as types and create objects from them. This tutorial builds a small Person class using properties and a constructor, then shows how records give you a shorter way to define simple data types.
Prerequisites
- The .NET SDK installed
- Basic C# syntax: variables, methods, and string interpolation
Step-by-Step Guide
Step 1: Define a class with properties
Properties expose data through get and set accessors. Using a private setter means only the class itself can change the value.
public class Person
{
public string Name { get; set; }
public int Age { get; private set; }
}Step 2: Add a constructor and methods
A constructor has the same name as the class and sets up the initial state. Expression-bodied members (=>) keep short methods compact.
public class Person
{
public string Name { get; set; }
public int Age { get; private set; }
public Person(string name, int age)
{
Name = name;
Age = age;
}
public void HaveBirthday() => Age++;
public string Describe() => $"{Name} is {Age} years old.";
}Step 3: Create and use objects
Use new to create an instance and call its methods.
var ava = new Person("Ava", 30);
ava.HaveBirthday();
Console.WriteLine(ava.Describe()); // Ava is 31 years old.Step 4: Use records for simple data
A record is a concise type for immutable data. Records compare by value, so two records with the same values are equal.
public record Point(int X, int Y);
var a = new Point(1, 2);
var b = new Point(1, 2);
Console.WriteLine(a == b); // TrueFAQs
- What is the difference between a field and a property?
- A field is a variable stored in a class. A property wraps access to data with get and set accessors, letting you add validation or restrict who can change a value.
- When should I use a record instead of a class?
- Use a record for data-focused types where value equality and immutability make sense, such as coordinates or API response models. Use a class for types with identity and changing state.
Summary
Classes bundle data and behavior, properties control access, and records give you compact, value-based types. Together they cover most everyday modeling needs in C#.
Comments
Log in or create a free account to join the discussion.