[. NET] Effective C # Quick notes-key additions to C # efficient programming

Source: Internet
Author: User
Tags cas

Effective C # Quick notes-key additions to C # efficient programming

Directory
    • 45. Minimize packing and unpacking
    • 46. Create a specialized exception class for your application
    • 47, the use of strong exception security guarantee
    • 48. Try to use secure code
    • 49. Implementing CLS-compliant assemblies
    • 50, the realization of small size, high cohesion assembly

This is the last article in this series.

45. Minimize packing and unpacking
    1. A value type is a container for data and does not support polymorphism.
    2. Boxing place a value type in a reference object of an indeterminate type, and let the value be used as a reference type. Unboxing refers to a copy of the value taken from the location of the reference type.
    3. Packing and unpacking are the means to compare the effect of performance, should be avoided as far as possible to avoid loading and unpacking operations.
    4. Generics can avoid unpacking operations.
    5. Value type boxing is implicit, hard to find and requires more attention.

46. Create a specialized exception class for your application

1. You should create different exception classes only if you think that users will use different forms to handle errors.

2. Custom exception classes should end with "Exception" and inherit System.Exception or other exception classes. However, you also need to include the constructor in the base class appropriately, and the content is given directly to the base class implementation.

    /// <summary>    ///Custom Exception Classes/// </summary>     Public classmyexception:exception { PublicMyException ():Base()        {        }         PublicMyException (strings):Base(s) {} PublicMyException (stringS, Exception e):Base(S, e) {}protectedMyException (SerializationInfo info, StreamingContext cxt):Base(info, cxt) {}}

3. When throwing your custom exception, you should store the original exception in the InnerException property so that you can display a friendly and informative exception:

         Public void Do ()        {            try            {                //doexception ();             }            catch  (doexception e)            {                var msg = $" the issue was deliberately caused by bloggers. " ;                 Throw New myexception (MSG, e);            }        }

4. Different types of exceptions should be thrown only when there are different types of recovery operations, and all constructors supported in the base class are provided when defining the exception class. Also, don't forget to use the InnerException property to save low-level exception information.

47, the use of strong exception security guarantee

1.Dave Abrahams defines 3 types of security anomalies to guarantee the program: Basic assurance, strong assurance, and no-throw guarantee.

2. Strong exception Guarantee: If an operation is interrupted because of an exception, the program will maintain the original state, the operation is either complete, or it will not modify any state of the program. The benefit of the strong exception guarantee: Whenever an exception is caught, all normal operations that will be attempted are not resumed, i.e. no further modifications are made. The current state of the program is the same as the operation has not started.

48. Try to use secure code
    1. The. NET runtime can guarantee that some of the code that is in the system does not penetrate directly to the remote computer for execution.
    2. Some code access security settings in the CLR, such as: The CLR enforces role-based security authentication to determine whether certain code can run under a specific role account.
    3. The CLR can check the IL code to ensure that it does not have potentially dangerous behavior. such as: direct access to raw memory.
    4. If your code does not require any security permissions, you do not need to use the CAS API to determine access rights, because this only affects performance and adds additional workload to the CLR.
    5. You can use the CAS API to access some of the protected resources, which generally require additional permissions. such as unmanaged memory and file system, registry, and so on.
    6. In general, the C # code that we write is safe unless you use/unsafe.
    7. You should avoid access to unmanaged memory whenever possible. It is really necessary to isolate it in a separate assembly.

49. Implementing CLS-compliant assemblies

1..NET the operating environment is language agnostic, and the assemblies we create must be compatible with the CLS to ensure that other developers can invoke your component in another language.

50, the realization of small size, high cohesion assembly
    1. If we all put all the code in an assembly, which is not conducive to the reuse of components, and not conducive to the local updating of the system, if it can be split into small assemblies, in the form of components for reuse, can be to a certain extent to simplify the subsequent development work.
    2. We use classes to encapsulate functionality and to store data, and only public classes, structs, and interfaces should be called contracts and accessed by other users (or assemblies).
    3. It is recommended that you split the program into multiple assemblies, putting the related types in the same assembly.
    4. An assembly should be a library that has a good organization that contains related functionality. If you do not know how to best particle size, you can tilt slightly in small and many directions.
    5. If all parameters and return values are interfaces, then any one assembly can easily be replaced with another assembly that implements the same interface.
    6. Smaller assemblies can also reduce the cost of program startup. Larger assemblies take more CPU time to load, and more time is required to compile the required IL into machine instructions. Although the code that will be called at startup is JIT-compiled, the assembly is loaded as a whole.
    7. Security checks become an additional overhead when you span assemblies. The smaller the number of times a program spans an assembly, the more efficiently it executes.
    8. The loss of performance is negligible for us because, at development time, we focus on the flexibility of the code, so don't worry about splitting large assemblies into small assembly performance issues.
    9. Common assemblies: small, focused assemblies that focus only on a particular feature, and larger assemblies that contain common functionality, regardless of the circumstances, should ensure that they are as small as reasonably possible, but should not be excessive.

This series

Effective C # Quick notes (i)-C # language habits

Effective C # Quick notes (ii)-. NET Resource Hosting

Effective C # quick Note (iii)-expressing design using C #

Effective C # Quick Notes (iv)-using frames

"Effective C #" Quick Notes (v)-dynamic Programming in C #

[. NET] Effective C # Quick notes-key additions to C # efficient programming

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.