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

Source: Internet
Author: User

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 the series. Maybe some theories may be out of date, I think it is still necessary, people's knowledge level is also a growing process, learn to stand on the shoulders of predecessors, try to learn and summarize constantly.

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. Boxing and unpacking can inadvertently create many copies, causing many difficult bugs to be discovered.

    4. Using interfaces instead of using types can avoid boxing, implement value types from an interface, and then invoke members through an interface.

    5. 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.

    6. Generics can avoid unpacking operations.

    7. Value type boxing is implicit, hard to find and requires more attention.

Here is a more detailed article on the loading and unpacking: "Packing and unpacking."

46. Create a specialized exception class for your application

1. You should create a different exception class only if the user handles the error in a different way.

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 class myexception:exception {public myexception (): base () {} public myexception (string s): base (s) {} public myexception (string s , Exception E): base (S, e) {} protected myexception (SerializationInfo info, StreamingContext cxt): base (info, cxt) {}}        

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

        void do ()        {            try            {                //doexception ();  Catchvar msg = $" This issue is intentionally caused by bloggers "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: There is a balance between recovering from exceptions and simplifying exception handling, and if an operation is interrupted because of an exception, the program will maintain its original state, the operation is either complete, or it will not modify any state of the program. The benefit of the strong exception guarantee: Any time you catch an exception, all normal operations that will be attempted will not proceed. The current state of the program is the same as the operation has not started.

3. Make a defensive copy of the data that will be modified, modify the defensive copy of the data, which may throw an exception and swap the temporary copy with the original object in case of an exception.

4. The target method bound by the finalizer, Dispose () method, and delegate object should in all cases ensure that they do not throw an exception.

48. Try to use secure code
    1. The. NET runtime can ensure that some malicious code does not penetrate directly to the remote machine for execution.

    2. Access security settings with code in the CLR, such as: CLR enforces role-based security authentication in order 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 there is no need to worry about splitting the large assemblies into small assemblies for performance issues.

    9. Common assemblies: small, focused assemblies that focus only on a particular feature, and larger assemblies that contain common functionality. In any case, it should be guaranteed to be as reasonable as 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 #

Effective C # Quick notes (vi)-C # efficient programming Essentials Supplement

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.