A constructor initializes new objects. C# also uses properties—get/set accessors—instead of verbose JavaBean getters for most types. Primary constructors (C# 12) shorten common patterns further.
Constructor and property example
class Product {
public string Sku { get; }
public double Price { get; private set; }
public Product(string sku, double price) {
Sku = sku;
Price = price;
}
}
this refers to the current instance. Auto-properties compile to backing fields—cleaner than public fields.
Init-only and required members
public required string Name { get; init; }
init allows setting during object construction but not afterward—useful for immutable DTO shapes without full records.
Important interview questions and answers
- Q: Property vs field?
A: Properties expose controlled access with logic in getters/setters; public fields skip validation and break encapsulation. - Q: What happens when you define any constructor?
A: The compiler no longer generates a parameterless constructor unless you add one explicitly.
Self-check
- What keywords define a read-only property set at construction?
- Why prefer properties over public fields?
Tip: Prefer auto-properties over public fields—add validation in setters when invariants matter.
Interview prep
- Property vs field?
Properties expose controlled access with getters/setters; public fields skip validation and break encapsulation.
- What happens when you define any constructor?
The compiler no longer generates a parameterless constructor unless you add one explicitly.