AVG 24th 2015 ADVANCED c# - part 1.

Slides:



Advertisements
Similar presentations
Coding Standard: General Rules 1.Always be consistent with existing code. 2.Adopt naming conventions consistent with selected framework. 3.Use the same.
Advertisements

Abstract Data Types Data abstraction, or abstract data types, is a programming methodology where one defines not only the data structure to be used, but.
C#.NET C# language. C# A modern, general-purpose object-oriented language Part of the.NET family of languages ECMA standard Based on C and C++
C# Programming: From Problem Analysis to Program Design1 Advanced Object-Oriented Programming Features C# Programming: From Problem Analysis to Program.
Reuse Activities Selecting Design Patterns and Components
Differences between C# and C++ Dr. Catherine Stringfellow Dr. Stewart Carpenter.
Object Based Programming. Summary Slide  Instantiating An Object  Encapsulation  Inheritance  Polymorphism –Overriding Methods –Overloading vs. Overriding.
Introduction to the Enterprise Library. Sounds familiar? Writing a component to encapsulate data access Building a component that allows you to log errors.
Programming Languages and Paradigms Object-Oriented Programming.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Algorithm Programming Bar-Ilan University תשס"ח by Moshe Fresko.
Lecture Set 11 Creating and Using Classes Part B – Class Features – Constructors, Methods, Fields, Properties, Shared Data.
Tuc Goodwin  Object and Component-Oriented Programming  Classes in C#  Scope and Accessibility  Methods and Properties  Nested.
Introduction to Exception Handling and Defensive Programming.
Introducing Allors Applications, Tools & Platform.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Introduction to c++ programming - object oriented programming concepts - Structured Vs OOP. Classes and objects - class definition - Objects - class scope.
Module 8: Delegates and Events. Overview Delegates Multicast Delegates Events When to Use Delegates, Events, and Interfaces.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 26 - Java Object-Based Programming Outline 26.1Introduction.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
Introduction to Object-Oriented Programming Lesson 2.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Today: –Review declaration, implementation, simple class structure. –Add an exception class and show.
Object-Based Programming in VB.NET. Must Understand Following: Encapsulation Information hiding Abstract Data Type Class, Instance, Reference Variable.
CIS 200 Test 01 Review. Built-In Types Properties  Exposed “Variables” or accessible values of an object  Can have access controlled via scope modifiers.
FIT Objectives By the end of this lecture, students should: understand the role of constructors understand how non-default constructors are.
C# Fundamentals An Introduction. Before we begin How to get started writing C# – Quick tour of the dev. Environment – The current C# version is 5.0 –
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
Patterns in programming
C# for C++ Programmers 1.
Creating and Using Objects, Exceptions, Strings
Andy Wang Object Oriented Programming in C++ COP 3330
Classes (Part 1) Lecture 3
Classes C++ representation of an object
Jim Fawcett CSE681 – SW Modeling & Analysis Fall 2014
CIS 200 Test 01 Review.
Inheritance and Polymorphism
Methods Chapter 6.
Chapter Eleven Handling Events.
Classes & Objects.
Array Array is a variable which holds multiple values (elements) of similar data types. All the values are having their own index with an array. Index.
Generics, Lambdas, Reflections
C++ History C++ was designed at AT&T Bell Labs by Bjarne Stroustrup in the early 80's Based on the ‘C’ programming language C++ language standardised in.
Intent (Thanks to Jim Fawcett for the slides)
Creating and Using Classes
.NET and .NET Core 5.2 Type Operations Pan Wuming 2016.
Object Based Programming
Optimizing Malloc and Free
Partnership.
Exception Handling Chapter 9.
6 Delegate and Lambda Expressions
Present by Andie Saizan, MCP
Chapter 6 Methods: A Deeper Look
Lecture 22 Inheritance Richard Gesick.
Andy Wang Object Oriented Programming in C++ COP 3330
Delegates & Events 1.
Object Oriented Practices
Lesson 7. Events, Delegates, Generics.
Dr. Bhargavi Dept of CS CHRIST
Tonga Institute of Higher Education
Lecture 5: Functions and Parameters
Generics, Lambdas, Reflections
How to organize and document your classes
5. 3 Coding with Denotations
Classes C++ representation of an object
European conference.
Jim Fawcett CSE681 – SW Modeling & Analysis Fall 2018
SPL – PS1 Introduction to C++.
Creating and Using Classes
Events, Delegates, and Lambdas
Presentation transcript:

AVG 24th 2015 ADVANCED c# - part 1

Advanced C# & tips and tricks Delegates Events Extensions Memory management

Tips and tricks 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

Tips and tricks Parameters with default value: Gives support for optional parameters Useful when we need to extend existing support without large changes

Tips and tricks Usage of enumerations as an alternative for Boolean parameters: Brings more information (clarity) Easier to extend

Tips and tricks Const variables vs static readonly, 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 – readonly are defined/assigned during the runtime Used primarily for reference types Allows value to be defined during declaration and inside constructor There is no special need to declare primitive constant as static readonly instead of as const. Yes, it’s possible later to supply just library (dll) with constant definition and entire solution will use A new value without rebuild. But in that case we have to rethink do we actually need a constant or Configuration parameter. So, const variables are something like macros and a bit faster than static readonly, but on other Side they require rebuilt of entire solution to utilize a new value.

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

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

Tips and tricks Exception handling: Do not reset exception stack trace. Use throw; statement

Tips and tricks 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 ! Same support can be implemented with Factory pattern which includes some configuration pulling !

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). When interface type is extended in the case of very common methods, it’s recommended to put extensions in the same namespace as original type, that way that functionality is automatically unlocked when user includes base class In the project. We can give as many as we want implementation for the interface not just one. We can switch between them by including specific namespace. Do not exaggerate with usage of extension methods. Think carefully do you need them. In the case if base class is owned by the user maybe better way is to extend directly base class.

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 a delegate object encapsulates a method

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 multicast delegate (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 ?!? This is trick question, both have its place where they are used. For simplest cases we will use delegates with anonymous functions, For more complicated we will still use delegates but which accept method target, And for the most complicated we will use template pattern in which code is decoupled into separated classes.

Delegates Why use it ?!?

Delegates 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

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 string manipulation parts of the code, make sure that it’s done in most efficient way Check whether some containers could be initialized with capacity flag: List<string> list = new List<string>(1200); All Disposable objects should be disposed at the end of usage. If application creates lots of temporary containers 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 redesign your code to create less as possible of small and temporary objects. GC will have less job and application will be more responsive.

Thank you Ivan Nemeš