TOC

This article is currently in the process of being translated into Arabic (~42% done).

C# 3.0:

Object Initializers

With C# 3.0, initializing both objects and collections have become much easier. Consider this simple Car class, where we use the automatic properties described in a previous chapter:

class Car
{
    public string Name { get; set; }
    public Color Color { get; set; }
}

Now, in C# 2.0, we would have to write a piece of code like this to create a Car instance and set its properties:

Car car = new Car();
car.Name = "Chevrolet Corvette";
car.Color = Color.Yellow;

It's just fine really, but with C# 3.0, it can be done a bit more cleanly, thanks to the new object initializer syntax:

Car car = new Car { Name = "Chevrolet Corvette", Color = Color.Yellow };

كما ترى، نستخدم مجموعة من الأقواس المعقوفة بعد إنشاء مثيل جديد للفئة (كائن) Car ، وداخلهم ، يمكننا الوصول إلى جميع الخصائص العامة لفئة Car. هذا يوفر قليلا من الكتابة ، وقليلا من المساحة كذلك. الجزء الرائع هو أنه يمكن عمل خصائص متداخلة أيضًا. بالنظر الى المثال التالي ، حيث نضيف خاصية معقدة جديدة إلى فئة Car، مثل هذا:

class Car
{
    public string Name { get; set; }
    public Color Color { get; set; }
    public CarManufacturer Manufacturer { get; set; }
}

class CarManufacturer
{
    public string Name { get; set; }
    public string Country { get; set; }
}

في الإصدار الـ C# 2 نقوم بتهيئة فئة جديدة من الفئة Car بهذه الطريقة :

Car car = new Car();
car.Name = "Corvette";
car.Color = Color.Yellow;
car.Manufacturer = new CarManufacturer();
car.Manufacturer.Name = "Chevrolet";
car.Manufacturer.Country = "USA";

بالإصدار الـ3 من لغة C# يمكننا فعل هذا الأمر بهذه الطريقة .

Car car = new Car { 
                Name = "Chevrolet Corvette", 
                Color = Color.Yellow, 
                Manufacturer = new CarManufacturer { 
                    Name = "Chevrolet", 
                    Country = "USA" 
                } 
            };

Or in case you're not too worried about readability, like this:

Car car = new Car { Name = "Chevrolet Corvette", Color = Color.Yellow, Manufacturer = new CarManufacturer { Name = "Chevrolet", Country = "USA" } };

Just like with the automatic properties, this is syntactical sugar - you can either use it, or just stick with the old, fashioned way of doing things.


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!