C# > Object-Oriented Programming (OOP) > Classes and Objects > Object Instantiation

Object Instantiation with Initialization

This snippet extends the basic object instantiation example by demonstrating how to initialize object properties directly during instantiation using object initializers.

Defining the Class

We define a `Car` class with properties for `Make`, `Model`, and `Year`. Importantly, we also include a default constructor (a constructor with no parameters). This is required for object initializer syntax to work.

public class Car
{
    public string Make { get; set; }
    public string Model { get; set; }
    public int Year { get; set; }

    // Default constructor (no parameters)
    public Car()
    {
    }
}

Object Instantiation with Object Initializers

In the `Main` method, we create an instance of the `Car` class using an object initializer. Instead of passing values to a constructor, we directly set the properties within curly braces `{}` after the `new Car()` expression. This provides a more concise and readable way to initialize object properties. Note that a default constructor (or a constructor that can be called without arguments due to optional parameters) is required for this syntax to work.

public class Program
{
    public static void Main(string[] args)
    {
        // Creating an instance of the Car class using object initializer
        Car myCar = new Car()
        {
            Make = "Toyota",
            Model = "Camry",
            Year = 2023
        };

        // Displaying the car's information
        Console.WriteLine($"My car is a {myCar.Year} {myCar.Make} {myCar.Model}.");
    }
}

Benefits of Object Initializers

  • Readability: Object initializers make the code more readable and easier to understand, especially when dealing with classes that have many properties.
  • Conciseness: They provide a more concise way to initialize object properties compared to calling a constructor with many parameters.
  • Flexibility: You can initialize only the properties you need to, leaving the others with their default values.

When to Use Object Initializers

Use object initializers when you want a more readable and concise way to initialize object properties, especially when the class has many properties or when you only need to initialize a subset of the properties. A default constructor is necessary for the compiler to understand the syntax.

Real-Life Use Case

Consider creating a user interface in a desktop application. You might have a `Button` class with properties like `Text`, `Width`, `Height`, `BackgroundColor`, and `Font`. Object initializers would be a very convenient way to create and configure `Button` objects with specific settings.

Best Practices

  • Ensure that your class has a default constructor (or a constructor that can be called without arguments) when using object initializers.
  • Use object initializers consistently throughout your codebase for improved readability.

Interview Tip

Be prepared to explain the syntax and benefits of object initializers. Understand that they are a syntactic sugar feature provided by C# to simplify object initialization.

FAQ

  • Why do I need a default constructor to use object initializers?

    Object initializers rely on the default constructor (or a constructor with optional parameters that can be called without any arguments) to create the object instance first. Then, the properties are set individually using the initializer syntax. Without a default constructor, the compiler wouldn't know how to create the initial object.
  • Can I use object initializers with constructors that have parameters?

    Yes, you can use object initializers with constructors that have parameters. The object initializers must come after the call to the parameterized constructor, and only set the properties that were not initialized by the constructor parameters. For example: `Car myCar = new Car("Ford") { Model = "Mustang", Year = 1967 };`