Normally in .NET 1.1 and 2.0, we define the class with
properties, then create the instance, and then define the values for properties either
in constructor or in the function which is using the object. Here, in C# 3.0 we can
define the values at the time of creation itself. Consider the following example
of class Icecream with two auto-implemented properties. Auto-implemented
properties are the properties without a local variable to hold the property value.
public class Icecream
{
public string Name { get; set; }
public double Price { get; set; }
}
Now when I create the new object of type Icecream, I can directly assign
values directly.
Icecream ice = new Icecream { Name = "Chocolate Fudge
Icecream", Price = 11.5 };
This is not only for the auto-implemented properties, but I can also assign a value
to any accessible field of the class. The following example has a field named
Cholestrol added to it.
public class Icecream
{
public string Name { get; set; }
public double Price { get; set; }
public string Cholestrol;
}
Now I can assign values to this new field added to the class at the time of creating
the object itself.
Pages:
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33