object-initialization syntax introduced for structs - CSharp Custom Type

CSharp examples for Custom Type:struct

Description

object-initialization syntax introduced for structs

Demo Code

using System;//from   w  ww .  ja v  a2 s  .c  o  m
public struct MyStruct
{
   public int n;
   public double d;
}
class Program
{
   static void Main(string[] args)
   {
      // Old-style initialization - default (to zeroes) or explicit (lines 2 & 3).
      MyStruct ms1 = new MyStruct(); // Initializes n and d to 0.
      ms1.n = 1;
      ms1.d = 2.0;
      Console.WriteLine("Old way: n = {0}, d = {1}", ms1.n, ms1.d);
      // New, more compact initialization syntax:
      MyStruct ms2 = new MyStruct { n = 3, d = 4.0 };
      Console.WriteLine("New syntax: n = {0}, d = {1}", ms2.n, ms2.d);
   }
}

Result


Related Tutorials