Page 188 - CSharp/C#
P. 188

Usage




        Initializers must evaluate to static expressions, just like field initializers. If you need to reference
        non-static members, you can either initialize properties in constructors like before, or use
        expression-bodied properties. Non-static expressions, like the one below (commented out), will
        generate a compiler error:


         // public decimal X { get; set; } = InitMe();  // generates compiler error

         decimal InitMe() { return 4m; }


        But static methods can be used to initialize auto-properties:


         public class Rectangle
         {
             public double Length { get; set; } = 1;
             public double Width { get; set; } = 1;
             public double Area { get; set; } = CalculateArea(1, 1);

             public static double CalculateArea(double length, double width)
             {
                 return length * width;
             }
         }


        This method can also be applied to properties with different level of accessors:


         public short Type { get; private set; } = 15;


        The auto-property initializer allows assignment of properties directly within their declaration. For
        read-only properties, it takes care of all the requirements required to ensure the property is
        immutable. Consider, for example, the FingerPrint class in the following example:


         public class FingerPrint
         {
           public DateTime TimeStamp { get; } = DateTime.UtcNow;

           public string User { get; } =
             System.Security.Principal.WindowsPrincipal.Current.Identity.Name;

           public string Process { get; } =
             System.Diagnostics.Process.GetCurrentProcess().ProcessName;
         }

        View Demo





        Cautionary notes







        https://riptutorial.com/                                                                             134
   183   184   185   186   187   188   189   190   191   192   193