Back to Blog
C#

C# Parameterized Constructor: Syntax and Usage

c# parameterized constructor: Learn how to define and use parameterized constructors in C# to initialize objects with required data, handle overloading, chaining, and...

C#constructorsobject initializationobject-oriented programmingclass design
A diagram showing a C# class with a parameterized constructor initializing object properties.

c# parameterized constructor requires a clear understanding of the core syntax, runtime behavior, and practical implementation patterns demonstrated in the examples below.

A parameterized constructor in C# is a constructor that accepts one or more arguments. It lets you create an object and set its initial state in a single expression, which is often more readable than creating an object and then assigning properties one by one. This article covers how to define parameterized constructors, overload them, chain them, and use them with inheritance, along with common mistakes and performance considerations.

What a Parameterized Constructor Does

A parameterized constructor is defined like any other constructor, but it takes parameters. These parameters are typically used to initialize instance fields or properties. The syntax is straightforward:

public class Product { public string Name { get; } public decimal Price { get; } public Product(string name, decimal price) { Name = name; Price = price; } }

Here, the Product class has a constructor that requires a name and a price. When you create a Product instance, you must provide both values:

var product = new Product("Laptop", 999.99m);

The constructor assigns the incoming values to the read-only properties. This pattern enforces that every Product has a name and a price from the moment it exists, which is useful for maintaining invariants.

Overloading Constructors with Different Parameters

A class can have multiple parameterized constructors with different parameter lists. This is called constructor overloading. It allows callers to choose the level of detail they want to provide at creation time.

public class User { public string Username { get; } public string Email { get; } public bool IsAdmin { get; } public User(string username, string email) : this(username, email, false) { } public User(string username, string email, bool isAdmin) { Username = username; Email = email; IsAdmin = isAdmin; } }

In this example, the two-parameter constructor calls the three-parameter constructor using this(), passing false for isAdmin. This reduces duplication of assignment logic. Overloading is useful when some parameters have sensible defaults, but you still want to enforce that certain data is always provided.

Using Constructor Chaining with this()

Constructor chaining is the practice of one constructor calling another in the same class. The this() keyword is used to invoke a sibling constructor. This is especially helpful when you have multiple constructors that share initialization logic.

public class Order { public int Id { get; } public DateTime CreatedAt { get; } public string CustomerName { get; } public Order(int id, string customerName) : this(id, customerName, DateTime.UtcNow) { } public Order(int id, string customerName, DateTime createdAt) { Id = id; CustomerName = customerName; CreatedAt = createdAt; } }

The first constructor delegates to the second, passing the current UTC time as the creation date. This keeps the default behavior in one place and makes the code easier to maintain. If the default logic changes later, you only need to update one constructor.

Parameterized Constructors in Inheritance

When a derived class has a parameterized constructor, it must call a constructor on the base class using base(). This ensures that the base class is initialized correctly before the derived class adds its own state.

public class Animal { public string Name { get; } public Animal(string name) { Name = name; } } public class Dog : Animal { public string Breed { get; } public Dog(string name, string breed) : base(name) { Breed = breed; } }

The Dog constructor passes name to the base constructor. If you omit the base() call, the compiler will try to call a parameterless constructor on Animal. If none exists, you'll get a compile error. This is a common source of confusion for developers new to inheritance in C#.

Common Mistakes and How to Avoid Them

One frequent mistake is forgetting to assign all constructor parameters to fields or properties. If a parameter is not used, it's usually a sign of a design problem. Another issue is not validating inputs. For example, a constructor that accepts a string might receive null or an empty string. It's often better to validate in the constructor so that invalid objects cannot be created.

public class Account { public string AccountNumber { get; } public Account(string accountNumber) { if (string.IsNullOrWhiteSpace(accountNumber)) throw new ArgumentException("Account number cannot be empty.", nameof(accountNumber)); AccountNumber = accountNumber; } }

This constructor throws an exception if the input is invalid, preventing the creation of an Account with an empty number. This is a form of defensive programming that keeps the object in a consistent state.

Another mistake is relying on a parameterless constructor when you have a parameterized one. If you define a constructor with parameters and don't explicitly define a parameterless one, the compiler removes the default parameterless constructor. Code that tries new MyClass() will fail unless you add a parameterless constructor explicitly.

When to Prefer Object Initializers Over Constructors

C# offers object initializers as an alternative to constructors for setting properties after creation. For example:

var product = new Product { Name = "Laptop", Price = 999.99m };

This works only if the properties have setters and the class has a parameterless constructor. Object initializers are convenient when you want to set only a subset of properties or when the class has many optional properties. However, they don't enforce required data at compile time. A parameterized constructor is better when you need to guarantee that certain values are always provided. Use a parameterized constructor when the object has a clear set of required fields, and use object initializers when most properties are optional and the object can exist in a partially initialized state.

Performance and Maintainability Considerations

Creating an object with a parameterized constructor is not significantly different in performance from creating one with a parameterless constructor and then assigning properties. The main cost is the constructor call itself, which is negligible in most applications. The real benefit is maintainability: a parameterized constructor makes the required dependencies explicit and centralizes initialization logic.

One thing to consider is that read-only properties can only be set from within a constructor. If you need immutable objects, a parameterized constructor is the standard way to achieve that. This can simplify reasoning about concurrency and reduce bugs in multi-threaded scenarios. However, if you have many optional parameters, the constructor can become unwieldy. In that case, consider the builder pattern or using optional parameters with default values, but be aware that optional parameters can hide required data.

Another operational concern is that constructors are called during object creation, so any heavy work inside a constructor will delay the creation. It's generally a good practice to keep constructors simple and avoid performing I/O or complex calculations. If you need to load data from a database or a file, do that in a factory method or a static method that returns an initialized object, rather than in the constructor itself.

Finally, when using dependency injection, parameterized constructors are the primary way to receive dependencies. The container inspects the constructor and provides the required services. This makes the dependencies explicit and testable, but it also means you should avoid doing too much work in the constructor, as that can make unit testing harder.

In summary, a parameterized constructor is a fundamental tool for creating well-formed objects in C#. It gives you compile-time safety for required data, supports overloading and chaining, and works naturally with inheritance. By understanding when to use it and when to use object initializers, you can write clearer and more maintainable code.

c# parameterized constructor: Practical Usage and Code Examp | RYUSLOG DEV