您的位置:首页 > 运维架构

C# Best Practices - Creating Good Properties

2016-01-12 18:18 330 查看

Coding Properties

Code in the Getter

Check the user's credentials

Check application state

Format the returned value

Log

Lazy Loading related data/object

Code in the Setter

Check the user's credentials

Check application state

Validate the incoming value

Log or change tracking

Format, convert, clean up

Best Practices

Do:

Add code in the getter to protect, format, initialize,...

Add code in the setter to protect, format, validate,...

Avoid:

Single character name

Abbreviations

Easy Way to Create

prop

propfull

Auto-Implemented Properties

Features

Concise property declaration

Implicit backing field

Don't allow code in the getter or setter

Best used for simple properties

Best Practices

Do:

Initialize on the declaration when needed

Avoid:

If property requires code in getter or setter

Property Accessibility

public string Category { get; set; }

protected string Category { get; set; }

internal string Category { get; set; }

protected internal string Category { get; set; }

private string Category { get; set; }

in getter or setter

public string Category { get; private set; }

internal string Category { get; private set; }

General rule:

Select the most restricted accessibility that still gets the job done.

Additional Use

1.Define concatenated values

public string FirstName { get; set; }
public string LastName { get; set; }

public string FullName
{
get { return FirstName + " " + LastName; }
}


2.Express calculations

public int Quantity { get; set; }
public int Price { get; set; }

public int LineItemTotal
{
get { return Quantity * Price; }
}


3.Expose related object properties

public Vendor ProductVendor { get; set; }

public string VendorName
{
get { return ProductVendor?.CompanyName; }
}


Expression-bodied Properties

For C# 6

public string FullName => FirstName + " " + LastName;

public int LineItemTotal => Quantity * Price;

public string VendorName => ProductVendor?.CompanyName;


Benefits of Properties

Fine grained access control

Execute code

Set break points or logging

Available for data binding

FAQ

1.What is the primary purpose of a property?

To guard access to the fields of the class

And optionally provide a location for logic when setter or getter

2.What are auto-implemented properties?

Short cut syntax for defining an implicit backing field with its associated property getter or setter.

3.When should you use an auto-implemented property?

When creating simple properties for a class.

4.When shouldn't you use an auto-implemented property?

If the property requires any code in the getter or setter.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: