1 / 37

Advanced C# Tips and Tricks: Delegates, Events, Extensions, and Memory Management

Learn advanced tips and tricks for C# programming, including the usage of delegates, events, extensions, and memory management techniques. Explore parameter labels, default values, enumerations, const variables, tuple classes, exception handling, and more.

bennettk
Download Presentation

Advanced C# Tips and Tricks: Delegates, Events, Extensions, and Memory Management

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. AVG 24th 2015 ADVANCED c# - part 1

  2. AdvancedC# & tipsandtricks Tips and tricks Delegates Events Extensions Memory management

  3. Tipsandtricks • Parameter labels: • Use parameter labels to additionally explain a function call • Useful when we have large number of primitive parameters, especially Booleans • Used when we want to define just one parameter but it’s in the middle of the list of default parameters

  4. Tipsandtricks • Parameters with default value: • Gives support for optional parameters • Useful when we need to extend existing support without large changes

  5. Tipsandtricks • Usage of enumerations as an alternative for Boolean parameters: • Brings more information (clarity) • Easier to extend

  6. Tipsandtricks • Const variables vs staticreadonly, pros and cons? • Const variables are directly ‘burned’ into the code • Used primarily for primitive types • Allows value to be defined only during declaration time • Static – readonlyare defined/assigned during the runtime • Used primarily for reference types • Allows value to be defined during declaration and inside constructor

  7. Tips and tricks • Proper usage of tuple class: • Easy way to group / wrap multiple objects

  8. Avoid nesting of tuple classes or its usage with too many parameters !! Tips and tricks

  9. Tipsandtricks • Exception handling: • Do not reset exception stack trace. Use throw; statement

  10. Tipsandtricks • Exception handling: • Do not mask exceptions !

  11. Extensions • Static methods which are used with instance syntax • Extension class should be defined as a static • Extension method requires parameter of class which is extended. • This parameter should be marked with ‘this’ keyword. • Can be used to extend system framework classes which are not owned

  12. Extensions • Useful to separate product or type specific functionality: • Ex1: Choice between fast support or memory efficient • Ex2: Choice between multiple supports for different productions • Make sure that namespaces which contain product specific support are exclusive

  13. Extensions • Can be used to extend interface with implemented methods • This way all classes which implement this interface are enriched automatically with those methods (LINQ support) • Can be used to decouple dependency between base class and unwanted class or even assembly. • Extension methods are used to unlock more advanced functionality of class (That way base API stays clean and simple for user).

  14. Delegates • Delegate is a type that presents reference to a method • Used to supply method as an argument to another method • Used to define callback method • Can be compared with C++ function pointers but they are type safe

  15. Delegates • We can associate instance of the delegate with any method containing compatible signature as delegate • We can associate both, static or instance methods

  16. Delegates • We can instantiate / supply delegate on a few ways:

  17. Delegates • We can instantiate / supply delegate on a few ways:

  18. Delegates • We can instantiate / supply delegate on a few ways:

  19. Delegates • We have two generic predefined C# delegates: • Action – for methods without return result • Function – for methods with return result

  20. Delegates • Delegates with out parameters: • Require types in anonymous function headers

  21. Delegates • Delegates can be combined together to form multicastdelegate (operator + is used) • Multicast delegate contains a list of delegates • When multicast delegate is called, all delegates in the list are invoked in exact order • Multicast delegates are base for C# events • The – operator can be used to remove a component delegate from multicast delegate

  22. Delegates • Delegates are objects like any other (with special purpose), we can: • Get list of component delegates • Get method info info of a delegate • Get class info of a delegate

  23. Delegates • But still, why use it ?!?

  24. Delegates • Why use it ?!?

  25. So, why use it ?!? • Callbacks • Divide abstraction from concrete implementation • Alternative to template function and strategy pattern • Dependency injection • Inversion of dependency • Policy injection • Events Delegates

  26. Events • Events provide a useful way for objects to signal state changes that may be useful to clients of the object • Events rely entirely on delegates support • Event property utilize a delegate definition • Used quite often in modern dynamically extendable architectures (pluggable systems)

  27. Events • Before declaring event in class, declare appropriate delegate • Event declaration follows:

  28. Events • Event invocation: • Hooking up to an event:

  29. Events • .NET framework guidelines: • Delegate type used for an event should take two parameters: source of the event and event info itself • Second parameter should be either EventArgs class itself or derived from it • Delegate name should indicate that it’s used as event handler / processor

  30. Events • There is predefined event handler in System namespace, use it for events that do not require any custom information.

  31. Memory management • Managed memory space divided into: • LOH (objects > 85 kb) • SOH • Generation 0 • Generation 1 • Generation 2

  32. Memory management • Possible problems with memory: • Memory fragmentation on the LOH -> OOME • Memory leaks (unmanaged resources) -> OOME • Performance issues

  33. Memory management • There are two types of garbage collector: • Workstation garbage collector • Server garbage collector

  34. Memory management • To enable server garbage collector: <configuration> <runtime> <gcServer enabled="true"/> </runtime> </configuration>

  35. Memory management • Good practice to prevent memory management issues: • Inspect stringmanipulation parts of the code, make sure that it’s done in most efficient way • Check whether some containers could be initialized with capacityflag: List<string> list = new List<string>(1200); • All Disposableobjects should be disposed at the end of usage. • If application creates lots of temporarycontainers with large object check is it possible to reuse those containers or to change their scope from function scope to higher.

  36. Memory management • Good practice to prevent memory management issues: • Check for unnecessary boxing and unboxing. • If some object are reusable, try to introduce a cache or a pool of the objects. • Use struct instead of the class for object definition in the case when object should be really small and composed of just a few primitive types. • In the end, try to redesignyour code to create less as possible of small and temporary objects. GC will have less job and application will be more responsive.

  37. Thankyou Ivan Nemeš

More Related