TExcelTAD
Home › C# › C# Class Members

C# Class Members

Everything declared inside a class is a member of that class. The most important kinds are fields, properties, methods and constructors; classes can also contain constants, events, indexers, operators and nested types.

Member Purpose Example
Field Stores data private int count;
Constant Fixed compile-time value public const int Max = 10;
Property Controlled access to data public string Name { get; set; }
Method Behaviour public void Reset() { … }
Constructor Initialises a new object public Timer(int seconds) { … }
Indexer Array-like access public int this[int i] => items[i];
Event Notifies subscribers public event Action? Changed;

Fields

Fields are variables declared directly in the class. They can have an initial value; otherwise they start with their type's default. Private fields are conventionally prefixed with an underscore.

csharp · try it yourself
using System;

var light = new TrafficLight();
Console.WriteLine(light.Describe());
light.Next();
light.Next();
Console.WriteLine(light.Describe());

class TrafficLight
{
    private readonly string[] _states = { "green", "yellow", "red" };
    private int _index;              // starts at 0
    public int Changes;              // public field (usually a property is better)

    public void Next()
    {
        _index = (_index + 1) % _states.Length;
        Changes++;
    }

    public string Describe() => 
quot;Light is {_states[_index]} after {Changes} changes"; }
Light is green after 0 changes
Light is red after 2 changes

Methods and the this keyword

Inside an instance method, this refers to the current object. You rarely need to write it, except to tell a field apart from a parameter with the same name, or to pass the current object somewhere.

csharp · try it yourself
using System;

var r = new Rectangle();
r.SetSize(4, 3);
Console.WriteLine(
quot;Area {r.Area()}, perimeter {r.Perimeter()}"); Console.WriteLine(r.IsLargerThan(new Rectangle())); class Rectangle { private double width; private double height; public void SetSize(double width, double height) { this.width = width; // field = parameter this.height = height; } public double Area() => width * height; public double Perimeter() => 2 * (width + height); public bool IsLargerThan(Rectangle other) => this.Area() > other.Area(); }
Area 12, perimeter 14
True

Properties (a first look)

A property looks like a field from the outside but is backed by code — usually a get accessor and a set accessor. The shortest form is the auto-property:

csharp · try it yourself
using System;

var p = new Product { Name = "Lamp", Price = 30m };
p.Price = 25m;
Console.WriteLine(
quot;{p.Name}: {p.Price}"); Console.WriteLine(p.PriceWithTax); class Product { public string Name { get; set; } = ""; public decimal Price { get; set; } public decimal PriceWithTax => Price * 1.2m; // computed, read-only }
Lamp: 25
30.0

Properties let you add validation or computation later without changing the code that uses the class. They are covered fully in the Properties lesson.

Indexers

An indexer lets objects be used with square brackets, like arrays:

csharp · try it yourself
using System;

var week = new Week();
Console.WriteLine(week[0]);
Console.WriteLine(week[6]);
Console.WriteLine(week["Wed"]);

class Week
{
    private readonly string[] _days = { "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" };

    public string this[int index] => _days[index];
    public int this[string name] => Array.IndexOf(_days, name);
}
Mon
Sun
2

Instance versus static members

Members are instance members by default: each object has its own field values, and methods work with one object. Members marked static belong to the class as a whole and are accessed through the class name (Math.PI, Console.WriteLine). The Static Members lesson goes into detail.

Tip: Keep fields private and expose data through properties and methods. That way the class stays in control of its own state.

Test yourself

What does this refer to inside an instance method?

  1. The class itself
  2. The current object
  3. The base class
  4. The calling method

Which member lets you write obj[3]?

  1. A property
  2. An indexer
  3. A constructor
  4. An event

What is the initial value of an int field that is not explicitly initialised?

  1. Undefined
  2. null
  3. 0
  4. -1