C# – What is the best way to give a C# auto-property an initial value?


In C# 5 and earlier, to give auto implemented properties an initial value, you have to do it in a constructor.

Since C# 6.0, you can specify initial value in-line. The syntax is:

public int X { get; set; } = x; // C# 6 or higher

DefaultValueAttribute is intended to be used by the VS designer (or any other consumer) to specify a default value, not an initial value. (Even if in designed object, initial value is the default value).

At compile time DefaultValueAttribute will not impact the generated IL and it will not be read to initialize the property to that value (see DefaultValue attribute is not working with my Auto Property).


What Is a Web Application?
Web applications are programs allowing better communication between businesses and their customers. …
How much can I earn from Google Adsense?
Google AdSense is a Google program that allows publishers to monetize their …

Blog at WordPress.com.

%d blogeri kao ovaj: