Posts

Showing posts from October, 2017

Property Accessibility

C# provides a standard set of accessibility modifiers for use on class members. public string Category { get; set; } Use public to grant access to the property from any code. this is very common, especially for properties that are defined in a business layer component, and are displayed and edited in a user component. protected string Category { get; set; } Protected most use often when working with inheritance and base class. internal string Category { get; set; } Internal limits access to only the component in which the property is defined. protected internal string Category { get; set; } Protected internal limits access to the same component and to inheritance classes. private string Category { get; set; } Private limits access to only the class in which the property is declared.

Expression-Bodied Properties

Image
What if we could change our concatenated property syntax from this to this? That's the purpose of the Expression-Bodied Properties that are new in C#6. They provide a syntax shortcut for  read-only properties that immediately return a value. Let's look a little closer at the syntax here. Notice that there are no curly braces, no get keyword and no return statement. Just a => some people call this "fat arrow syntax"   but technically its called a Lambda operator. Here some few example. FullName property that is the concatenation of the first and the last names.  ItemTotal that calculates the total from the Quantity and price. VendorName, which exposes the ProductVendor's CompanyName. Each of these takes up one line of code instead of the original three.  

Auto-Implemented Properties

We've created fields and properties the hard way, we've declared the field and creating the property with getter and setter. We have been saving some typing by using the visual studio "propfull" snippet that generated the structure of this code for us. but there is an easier way. With C# auto-implemented properties, it is fast and easy to create the properties for our application. Concise property declaration Auto-implemented properties provide a more concise property declaration. Implicit backing field notice there is no field declared when using auto-implemented properties. A private backing field is declared implicitly behind the scenes,  so instead of writing six line of code for each property, we can define each property in one line of code.   Don't allow code in the getter or setter Auto-Implemented Properties any code in the getter or the setter. Best used for simple properties That don't require any additional logic or proces...