Classes and Objects

View saved

Define a class

A class groups data and behavior. Create instances with new.

class User
{
    public string Name;
    public int Age;

    public User(string name, int age)
    {
        Name = name;
        Age = age;
    }
}

var u = new User("Ada", 28);
Console.WriteLine(u.Name);

Add a method

Instance methods use the object's fields.

public string Label() => $"{Name} ({Age})";

Reference semantics

Class instances are reference types. Assigning copies the reference, not a deep clone.

var a = new User("Ada", 28);
var b = a;
b.Age = 29;
Console.WriteLine(a.Age); // 29

Class tips

  • One public class per file is a common convention
  • Keep fields private and expose properties (next lesson)
  • Static members belong to the type, not an instance
  • Records offer concise immutable data types in modern C#

Comments

One comment per signed-in account. Comments are saved with this page’s URL.