Properties and accessors: C# and Java

A property is a member that reads like a field and runs like a method. C# has had it since the first version and the compiler writes the accessor methods; Java has no property syntax and a reader writes the methods, or uses a record for the immutable case. The task is small: a person with a name and a birth year, a point with a computed length, and a settings object whose members must be set once.

The task in C#

Three shapes of the same idea: a class with a primary constructor and read-only properties, a record with a computed property, and a class with required and init members that an object initialiser must fill:

Console.WriteLine("properties 1.0"); var person = new Person("Ada", 1815); Console.WriteLine($"{person.Name} born {person.BirthYear}"); Console.WriteLine($"age in 1850 {person.AgeIn(1850)}"); var point = new Point(3, 4); Console.WriteLine($"{point} length {point.Length:F1}"); try { var empty = new Person("", 1815); Console.WriteLine(empty.Name); } catch (ArgumentException ex) { Console.WriteLine($"refused {ex.Message}"); } var settings = new Settings { Host = "localhost", Port = 8080 }; Console.WriteLine($"{settings.Host}:{settings.Port}"); sealed class Person(string name, int birthYear) { public string Name { get; } = name.Length == 0 ? throw new ArgumentException("name is empty", nameof(name)) : name; public int BirthYear { get; } = birthYear; public int AgeIn(int year) => year - BirthYear; } sealed record Point(int X, int Y) { public double Length => Math.Sqrt((X * X) + (Y * Y)); } sealed class Settings { public required string Host { get; init; } public required int Port { get; init; } }

dotnet run
echo "status: $?"

properties 1.0
Ada born 1815
age in 1850 35
Point { X = 3, Y = 4, Length = 5 } length 5.0
refused name is empty (Parameter 'name')
localhost:8080
status: 0

The same task in Java

The same three shapes with the tools Java has: a final class with private fields and getters, a record with a method for the length, and a record whose canonical constructor is the only way to set the values:

public class Properties { public static void main(String[] args) { System.out.println("properties 1.0"); Person person = new Person("Ada", 1815); System.out.println(person.getName() + " born " + person.getBirthYear()); System.out.println("age in 1850 " + person.ageIn(1850)); Point point = new Point(3, 4); System.out.println(point + " length " + String.format("%.1f", point.length())); try { Person empty = new Person("", 1815); System.out.println(empty.getName()); } catch (IllegalArgumentException ex) { System.out.println("refused " + ex.getMessage()); } Settings settings = new Settings("localhost", 8080); System.out.println(settings.host() + ":" + settings.port()); } static final class Person { private final String name; private final int birthYear; Person(String name, int birthYear) { if (name.isEmpty()) { throw new IllegalArgumentException("name is empty"); } this.name = name; this.birthYear = birthYear; } String getName() { return name; } int getBirthYear() { return birthYear; } int ageIn(int year) { return year - birthYear; } } record Point(int x, int y) { double length() { return Math.sqrt(x * x + y * y); } } record Settings(String host, int port) { } }

javac -g -d out Properties.java
java -cp out Properties
echo "status: $?"

properties 1.0
Ada born 1815
age in 1850 35
Point[x=3, y=4] length 5.0
refused name is empty
localhost:8080
status: 0

What differs

The next page compares the query: LINQ in C# and the Stream API in Java, on the same four orders.

Exercises

  1. Add a setter for the birth year in Java and decide what the C# equivalent is.
  2. Give the C# settings class a third optional member with a default and fill it in only one initialiser.
  3. Write a Java builder for the settings object and compare the call site with the C# initialiser.
  4. Move the validation of the name into a static factory in both languages.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does a C# property compile to?

    Answer

    A pair of accessor methods, get and set

    The syntax is a member; the compiler writes the accessors.

  2. What does init allow that set does not?

    Answer

    A write in an object initialiser, and never after

    The page sets the members in the initialiser and nowhere else.

  3. What does this program print? var p = new Person("Ada"); Console.WriteLine(p.Name); sealed class Person(string name) { public string Name { get; } = name; }

    Answer

    Ada

    The get-only property returns the value the constructor stored.

  4. What does required do in C#?

    Answer

    It makes the compiler demand a value in the initialiser

    The settings object cannot be created without Host and Port.

  5. What does this program print? var p = new Point(3, 4); Console.WriteLine($"{p.Length:F0}"); record Point(int X, int Y) { public double Length => Math.Sqrt((X * X) + (Y * Y)); }

    Answer

    5

    The computed length of the point is the measured 5.

  6. How does Java expose a value without property syntax?

    Answer

    A private field and a public getter method

    The page shows getName and getBirthYear.

  7. What does this program print? try { var p = new Person(""); Console.WriteLine(p.Name); } catch (ArgumentException ex) { Console.WriteLine(ex.Message); } sealed class Person(string name) { public string Name { get; } = name.Length == 0 ? throw new ArgumentException("name is empty") : name; }

    Answer

    name is empty

    The message of the C# exception is the text of the property initialiser.

  8. Why does the C# record print Length in its ToString?

    Answer

    A record lists every public property, computed ones included

    The measured line reads Point { X = 3, Y = 4, Length = 5 }.

  9. What does this program print? var p = new Person("Ada", 1815); Console.WriteLine($"{p.Name} {p.BirthYear}"); sealed class Person(string name, int birthYear) { public string Name { get; } = name; public int BirthYear { get; } = birthYear; }

    Answer

    Ada 1815

    Two members of the same object, in the order of the format string.

  10. Which member can a Java record have?

    Answer

    A method, such as length(), but no setters

    The record in the page has a length method and no way to change its components.

The C# program was built with the .NET SDK 10.0.303 and the Java program with OpenJDK 21.0.13.1 (javac 21.0.13.1), both run on Alpine Linux 3.24.3 (x86_64, four processors) in a Docker container.

Article author: Arthur Isaev

Banner image