Main Article - The New Features of C # 3.0
Today I am speaking to you from another feature introduced with C # 3.0 which is the Object Initializers, which initialize objects of a more compact and fast that the traditional.
With this feature we can initialize the properties of an object once in the same statement, using braces, as will be seen in following example.
In this example, we created a class with some properties Citizen. In the main function, we have the first statement of the subject bill of the traditional way, then the declaration of the object steve through object initializers:
using System; namespace ConsoleApplication ( class Program ( static void Main (string [] args) ( Citizen Citizen bill = new (); bill.Age = 40; bill.FirstName = "Bill"; bill.LastName = "Gates"; bill.Gender = Genders.Male; bill.PrintInfo (); Citizen Citizen steve = new () (FirstName = "Steve", LastName = "Jobs", Age = 43, Gender = Genders.Male); steve.PrintInfo (); Console.ReadKey (); ) ) public enum Genders ( Male = 0, Female = 1 ) public class Citizen ( private string firstname; private int age; private string LastName; private Genders gender; public string FirstName ( get (return FirstName;) set (firstname = value;) ) public int Age ( get (return age;) set (age = value;) ) public string LastName ( get (return LastName;) set (LastName = value;) ) public Genders Gender ( get (return gender;) set (gender = value;) ) public void PrintInfo () ( Console.WriteLine ( "Name: (0) \ nLastName: (1) \ NAgE: (2) \ nGender: (3)", FirstName, LastName, age, gender); ) ) )
The Object Initializers become especially useful when used in conjunction with LINQ, the query expressions. In select clause, the query expression can change in the query, the objects we want to select. Thus we can obtain only the data you want, for example, image you wanted to know only the first and last name of the type of objects Citizen. In this case this would have a select genre:
citizenNames var c = from citizens in select new (c.FirstName, c.LastName); foreach (var cit in citizenNames) ( Console.WriteLine ( "(0) (1)", cit.FirstName, cit.LastName); )
The purpose citizenNames, contains only the objects with new properties FirstName and LastName. With the Object Initializers can even change the name of the property, using the following syntax:
citizenNames var c = from citizens in select new (c.FirstName, Name = c.LastName); foreach (var cit in citizenNames) ( Console.WriteLine ( "(0) (1)", cit.FirstName, cit.Name); )
Again, we can see that with the use of new functionality in C # 3.0 shorten the number of lines of code produced.
If you liked this article subscribe to the RSS feed istomesmo to stay updated on the latest articles.
Learn more about RSS fedde here
Articles that may interest you:



