Using the object initializer feature - CSharp Custom Type

CSharp examples for Custom Type:Object Initializer

Description

Using the object initializer feature

Demo Code

using System;/*from  w  w w.  j  a  v a 2  s.c o m*/
class Program
{
   static void Main(string[] args)
   {
      // The old way of initializing a Student's properties.
      Student nicholas = new Student();
      nicholas.Name = "Nicholas";
      nicholas.Address = "8 Main Street, Las Vegas, NM 89000";
      nicholas.GradePointAverage = 3.51;
      PrintStudentInfo(nicholas);
      Student randal = new Student
      {
         Name = "new ",
         Address = "123 Main Street, Las Vegas, NM 00000",
         GradePointAverage = 3.51
      };
      PrintStudentInfo(randal);
      LatitudeLongitude latLong = new LatitudeLongitude() { Latitude = 35.3, Longitude = 104.9 };
      Console.WriteLine("Latitude {0}, Longitude {1}", latLong.Latitude, latLong.Longitude);
      Rectangle rect = new Rectangle
      {
         UpperLeftCorner = new Point { X = 3, Y = 4 },
         LowerRightCorner = new Point { X = 5, Y = 6 }
      };
      Console.WriteLine("Rectangle with upper left corner at ({0},{1}) and "
      + "lower right corner at ({2},{3})", rect.UpperLeftCorner.X, rect.UpperLeftCorner.Y,
      rect.LowerRightCorner.X, rect.LowerRightCorner.Y);
   }
   private static void PrintStudentInfo(Student student)
   {
      Console.WriteLine("Name: {0}\nAddress: {1}\nGPA: {2}",
      student.Name, student.Address, student.GradePointAverage);
   }
}
public class Student
{
   public string Name { get; set; }
   public string Address { get; set; }
   public double GradePointAverage { get; set; }
}
public class LatitudeLongitude
{
   public double Latitude { get; set; }
   public double Longitude { get; set; }
}
public class Point
{
   public int X { get; set; }
   public int Y { get; set; }
}
public class Rectangle
{
   public Point UpperLeftCorner { get; set; }
   public Point LowerRightCorner { get; set; }
}

Result


Related Tutorials