C# Best Practices - Accessing and Using Classes

References and Using

Do:

Take care when defining references

References must be one way (or circular dependency error)

Take advantage of the using directive

Avoid:

Excessive use of the using static directive

Object vs. Class

Object:

Represents one special thing (Example:Hammer or Saw)

Defines one thing created from that template

Created at runtime with the new keyword

Class:

Represens things of the same type (Example:Product)

Define the template specifying the data and processing associated with all things of that type

Created at develop time with code

Static class doesn't create object

Object initialization

3 Ways to initialize object:

1.Setting properties

Easy to debug

When populating from database values

When modifying properties

2.Parameterized constructor

When setting the basic set of properties

3.Object initializers

When readability is important

When initializing a subset or superset of properties

Instantiating Related Objects

Usage Scenarios

One method, Always, Sometimes

One method

Initialize in the method that needs it

public string SayHello()
{
    var vendor = new Vendor();
    var vendorGreeting = vendor.SayHello();
}

Always

Define a property

private Vendor productVendor;
public Vendor ProductVendor
{
    get { return productVendor; }
    set { productVendor = value; }
}
public Product()
{
this.ProductVendor = new Vendor();
}

Sometimes

Define a property

Initialize in the property setter

"Lazy Loading"

private Vendor productVendor;
public Vendor ProductVendor
{
    get
    {
        if (productVendor = null)
        {
            productVendor = new Vendor();
        }
        return productVendor;
    }
    set { productVendor = value; }
}

 Null Checking

if (currentProduct != null && currentProduct.ProductVendor != null)
{
    var companyName = currentProduct.ProductVendor.CompanyName;
}

C# 6 New Features

var companyName = currentProduct?.ProductVendor?.CompanyName;

"If null then null,it not then dot."

FAQ

1.What's the difference between an object and a class?

A class is a template that specifies the data and operations for an entity.

An object is an instance of that class created at runtime using the new keyword.

2.What is lazying loading and when would you use it?

Instantiating related objects when they are needed and not before.

This often involves creating the instance in the property getter for the related object

你可能感兴趣的:(C# Best Practices - Accessing and Using Classes)