370 likes | 381 Views
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.
E N D
AVG 24th 2015 ADVANCED c# - part 1
AdvancedC# & tipsandtricks Tips and tricks Delegates Events Extensions Memory management
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
Tipsandtricks • Parameters with default value: • Gives support for optional parameters • Useful when we need to extend existing support without large changes
Tipsandtricks • Usage of enumerations as an alternative for Boolean parameters: • Brings more information (clarity) • Easier to extend
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
Tips and tricks • Proper usage of tuple class: • Easy way to group / wrap multiple objects
Avoid nesting of tuple classes or its usage with too many parameters !! Tips and tricks
Tipsandtricks • Exception handling: • Do not reset exception stack trace. Use throw; statement
Tipsandtricks • Exception handling: • Do not mask exceptions !
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
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
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).
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
Delegates • We can associate instance of the delegate with any method containing compatible signature as delegate • We can associate both, static or instance methods
Delegates • We can instantiate / supply delegate on a few ways:
Delegates • We can instantiate / supply delegate on a few ways:
Delegates • We can instantiate / supply delegate on a few ways:
Delegates • We have two generic predefined C# delegates: • Action – for methods without return result • Function – for methods with return result
Delegates • Delegates with out parameters: • Require types in anonymous function headers
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
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
Delegates • But still, why use it ?!?
Delegates • Why use it ?!?
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
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)
Events • Before declaring event in class, declare appropriate delegate • Event declaration follows:
Events • Event invocation: • Hooking up to an event:
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
Events • There is predefined event handler in System namespace, use it for events that do not require any custom information.
Memory management • Managed memory space divided into: • LOH (objects > 85 kb) • SOH • Generation 0 • Generation 1 • Generation 2
Memory management • Possible problems with memory: • Memory fragmentation on the LOH -> OOME • Memory leaks (unmanaged resources) -> OOME • Performance issues
Memory management • There are two types of garbage collector: • Workstation garbage collector • Server garbage collector
Memory management • To enable server garbage collector: <configuration> <runtime> <gcServer enabled="true"/> </runtime> </configuration>
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.
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.
Thankyou Ivan Nemeš