Presentation is loading. Please wait.

Presentation is loading. Please wait.

© FPT Software Advanced features in C# 1. © FPT Software Agenda Attributes Delegates & Events Anonymous Types & Dynamic Type Extension Methods Lambda.

Similar presentations


Presentation on theme: "© FPT Software Advanced features in C# 1. © FPT Software Agenda Attributes Delegates & Events Anonymous Types & Dynamic Type Extension Methods Lambda."— Presentation transcript:

1 © FPT Software Advanced features in C# 1

2 © FPT Software Agenda Attributes Delegates & Events Anonymous Types & Dynamic Type Extension Methods Lambda Expressions Reflection Preprocessor Directives Garbage Collection Q&A 2

3 © FPT Software Agenda Attributes Delegates & Events Anonymous Types & Dynamic Type Extension Methods Lambda Expressions Reflection Preprocessor Directives Garbage Collection Q&A 3

4 © FPT Software Attributes It’s often necessary to associate information (metadata) with types and members, e.g. –Documentation URL for a class –Transaction context for a method –XML persistence mapping –COM ProgID for a class –Attributes allow you to decorate a code element Assembly, module, type, member, return value and parameter) with additional information 4

5 © FPT Software Attributes 5 Create new DisplayName attribute Apply DisplayName to add metadata for enum

6 © FPT Software Attributes Attributes are superior to the alternatives –Modifying the source language –Using external files, e.g.,.IDL,.DEF Attributes are extensible –Attributes allow to you add information not supported by C# itself –Not limited to predefined information Built into the.NET Framework, so they work across all.NET languages –Stored in assembly metadata 6

7 © FPT Software Attributes Attribute Name Description Browsable Should a property or event be displayed in the property window Serializable Allows a class or struct to be serialized Obsolete Compiler will complain if target is used ProgId COM Prog ID Transaction Transactional characteristics of a class 7 Some predefined.NET Framework attributes

8 © FPT Software Agenda Attributes Delegates & Events Anonymous Types & Dynamic Type Extension Methods Lambda Expressions Reflection Preprocessor Directives Garbage Collection Q&A 8

9 © FPT Software Delegates A delegate is a reference type that defines a method signature A delegate instance holds one or more methods –Essentially an “object-oriented function pointer” –Methods can be static or non-static –Methods can return a value Provides polymorphism for individual functions Foundation for event handling 9

10 © FPT Software Events Events are well suited for user-interfaces –The user does something (clicks a button, moves a mouse, changes a value, etc.) and the program reacts in response Many other uses, e.g. –Time-based events –Asynchronous operation completed –Email message has arrived –A web session has begun 10

11 © FPT Software Events C# has native support for events Based upon delegates An event is essentially a field holding a delegate However, public users of the class can only register delegates –They can only call += and -= –They can’t invoke the event’s delegate Multicast delegates allow multiple objects to register with the same event 11

12 © FPT Software Events - Example 12 Declare click event for MyButton class Handler click event with btnOk_Click method

13 © FPT Software Agenda Attributes Delegates & Events Anonymous Types & Dynamic Type Extension Methods Lambda Expressions Reflection Preprocessor Directives Garbage Collection Q&A 13

14 © FPT Software Anonymous Types An anonymous class is a local class that does not have a name. An anonymous class allows an object to be created using an expression that combines object creation with the declaration of the class. This avoids naming a class, at the cost of only ever being able to create one instance of that anonymous class. 14

15 © FPT Software Anonymous Types An anonymous class is defined as part of a new expression and must be a subclass or implement an interface The class body can define methods but cannot define any constructors. The restrictions imposed on local classes also apply 15 new className( argumentList ) { classBody } new interfaceName() { classBody }

16 © FPT Software Anonymous Types 16 Create new Anonymous type with two properties are Color & Price

17 © FPT Software Dynamic Types 17 Calculator calc = GetCalculator(); int sum = calc.Add(10, 20); Calculator calc = GetCalculator(); int sum = calc.Add(10, 20); object calc = GetCalculator(); Type calcType = calc.GetType(); object res = calcType.InvokeMember("Add", BindingFlags.InvokeMethod, null, new object[] { 10, 20 }); int sum = Convert.ToInt32(res); object calc = GetCalculator(); Type calcType = calc.GetType(); object res = calcType.InvokeMember("Add", BindingFlags.InvokeMethod, null, new object[] { 10, 20 }); int sum = Convert.ToInt32(res); ScriptObject calc = GetCalculator(); object res = calc.Invoke("Add", 10, 20); int sum = Convert.ToInt32(res); ScriptObject calc = GetCalculator(); object res = calc.Invoke("Add", 10, 20); int sum = Convert.ToInt32(res); dynamic calc = GetCalculator(); int sum = calc.Add(10, 20); dynamic calc = GetCalculator(); int sum = calc.Add(10, 20); Statically typed to be dynamic Dynamic method invocation Dynamic conversion

18 © FPT Software Dynamic Types When operand(s) are dynamic… Member selection deferred to run-time At run-time, actual type(s) substituted for dynamic Static result type of operation is dynamic 18 dynamic x = 1; dynamic y = "Hello"; dynamic z = new List { 1, 2, 3 }; dynamic x = 1; dynamic y = "Hello"; dynamic z = new List { 1, 2, 3 }; Compile-time type dynamic Run-time type System.Int32

19 © FPT Software Dynamic Types 19 public static class Math { public static decimal Abs(decimal value); public static double Abs(double value); public static float Abs(float value); public static int Abs(int value); public static long Abs(long value); public static sbyte Abs(sbyte value); public static short Abs(short value);... } public static class Math { public static decimal Abs(decimal value); public static double Abs(double value); public static float Abs(float value); public static int Abs(int value); public static long Abs(long value); public static sbyte Abs(sbyte value); public static short Abs(short value);... } double x = 1.75; double y = Math.Abs(x); double x = 1.75; double y = Math.Abs(x); dynamic x = 1.75; dynamic y = Math.Abs(x); dynamic x = 1.75; dynamic y = Math.Abs(x); Method chosen at compile-time: double Abs(double x) Method chosen at run-time: double Abs(double x) dynamic x = 2; dynamic y = Math.Abs(x); dynamic x = 2; dynamic y = Math.Abs(x); Method chosen at run-time: int Abs(int x)

20 © FPT Software Agenda Attributes Delegates & Events Anonymous Types & Dynamic Type Extension Methods Lambda Expressions Reflection Preprocessor Directives Garbage Collection Q&A 20

21 © FPT Software Extension Methods Extends Existing Types Adds Methods Without Derivation Accesses Public Members of Extended Types Must be: –public and static –Housed within a static class Use this keyword before parameter of extended type 21

22 © FPT Software Extension Methods 22 Create new Extension method ConvertToNumber for string type Use ConvertToNumber method to convert string to int

23 © FPT Software Agenda Attributes Delegates & Events Anonymous Types & Dynamic Type Extension Methods Lambda Expressions Reflection Preprocessor Directives Garbage Collection Q&A 23

24 © FPT Software Lambda Expressions A lambda expression is an anonymous function. Lambdas are used in method-based LINQ queries as arguments to standard query operator methods A lambda expression with an expression on the right side of the => operator is called an expression lambda (input parameters) => expression A statement lambda resembles an expression lambda except that the statement(s) is enclosed in braces: (input parameters) => {statement;} 24

25 © FPT Software Lambda Expressions Many Standard query operators have an input parameter whose type is one of the Func family of generic delegatesFunc<T, TResult> These delegates use type parameters to define the number and types of input parameters, and the return type of the delegate. 25

26 © FPT Software Agenda Attributes Delegates & Events Anonymous Types & Dynamic Type Extension Methods Lambda Expressions Reflection Preprocessor Directives Garbage Collection Q&A 26

27 © FPT Software Reflection Reflection is the feature in.Net, which enables us to get some information about object in runtime. 27 Information about object Data of class Names of the methods Constructors of that object

28 © FPT Software Reflection - Why reflection Explore assembly metadata Creating objects dynamically Invoking methods dynamically Write “generic” code that works with different types Implement sophisticated programming techniques 28

29 © FPT Software Reflection - Reflection Core Concepts Metadata –Single location for type information and code –Code is literally contained within type information –Every.NET object can be queried for its type –Type metadata can be explored with Reflection Dynamic Type System –Highly dynamic and language independent –Types may be extended and built at run time –Allows on-the-fly creation of assemblies –See my CodeDom tutorial http://www.codeproject.com/KB/dotnet/CodeDomDelegates.aspx 29

30 © FPT Software Reflection 30 [serializable] public class Person : { public event OnSaveChange onsv; public Date DOB; public string FirstName; public string LastName; public string Name { get { return FirstName + " " + LastName; } } public Person(string First,string Last) { FirstName=First;LastName=Last; } public bool Save() { System.Type t = this.GetType() ; foreach( FieldInfo f in t.GetFields() ) {... } } System.Type Attributes Fields Properties Constructors Methods Events Parameters

31 © FPT Software Reflection Accessing meta-data: System.Object.GetType() –All.NET classes (implicitly) inherit System.Object –Available on every.NET class; simple types too Explicit language support for type meta-data –C#, JScript.NET: typeof(…) –VB.NET: If TypeOf … Is … Then … Determining Type Identity –Types have unique identity across any assembly –Types can be compared for identity if ( a.GetType() == b.GetType() ) { … }; 31

32 © FPT Software Reflection – System Type Provides access to metadata for any.NET type Returned by System.Object.GetType() Allows drilling down into all facets of a type –Category: Simple, Enum, Struct or Class –Methods and Constructors, Parameters and Return –Fields and Properties, Arguments and Attributes –Events, Delegates, and Namespaces 32

33 © FPT Software Reflection - Example 33

34 © FPT Software Reflection – MemberInfo Base class for all "member" element descriptions –Fields, Properties, Methods, etc. Provides member kind, name, and declaring class 34 MemberInfo MethodBase ParameterInfo FieldInfo EventInfo PropertyInfo MethodInfo ConstructorInfo

35 © FPT Software Reflection Access to meta-data for any.NET type Returned by System.Object.GetType() Allows drilling down into all facets of a type Category: Simple, Enum, Struct or Class Methods and Constructors, Parameters and Return Fields and Properties, Arguments and Attributes Events, Delegates and Namespaces C# also has the, typeof(), is and as operators. 35

36 © FPT Software Reflection Finding and Exploring Members –MemberInfo: GetMembers(), FindMembers() Exploring Fields and Properties –FieldInfo: GetFields(), PropertyInfo: GetProperties() Exploring Constructors, Methods and Events –GetConstructors(), GetMethods(), GetEvents() Exploring attributes, determining implemented interfaces, enumerating nested types, … Summary: Everything you may ever want to know 36

37 © FPT Software Agenda Attributes Delegates & Events Anonymous Types & Dynamic Type Extension Methods Lambda Expressions Reflection Preprocessor Directives Garbage Collection Q&A 37

38 © FPT Software Preprocessor Directives –C# provides preprocessor directives that serve a number of functions –Unlike C++, there is not a separate preprocessor The “preprocessor” name is preserved only for consistency with C++ –C++ preprocessor features removed include: #include: Not really needed with one-stop programming; removal results in faster compilation Macro version of #define: removed for clarity 38

39 © FPT Software Preprocessor Directives DirectiveDescription #define, #undefDefine and undefine conditional symbols #if, #elif, #else, #endifConditionally skip sections of code #error, #warningIssue errors and warnings #region, #endDelimit outline regions #lineSpecify line number 39

40 © FPT Software Preprocessor Directives - Conditional Compilation 40 #define Debug public class Debug { [Conditional("Debug")] public static void Assert(bool cond, String s) { if (!cond) { throw new AssertionException(s); } void DoSomething() {... // If Debug is not defined, the next line is // not even called Assert((x == y), “X should equal Y”);... }

41 © FPT Software Preprocessor Directives - Assertions –By the way, assertions are an incredible way to improve the quality of your code –An assertion is essentially a unit test built right into your code –You should have assertions to test preconditions, postconditions and invariants –Assertions are only enabled in debug builds –Your code is QA’d every time it runs 41

42 © FPT Software Agenda Attributes Delegates & Events Anonymous Types & Dynamic Type Extension Methods Lambda Expressions Reflection Preprocessor Directives Garbage Collection Q&A 42

43 © FPT Software Garbage Collection –Memory Management technique. –Process of freeing objects. –No longer referenced by the program. 43

44 © FPT Software Garbage Collection – Why Garbage Collection –Free unreferenced objects. –Combat heap fragmentation. –Relieves programmer from manual freeing the memory. –Helps in ensuring program integrity. –Disadvantages Extra Overhead. Less control over scheduling of CPU time. 44

45 © FPT Software Garbage Collection – The.Net way –Microsofts.NET common language runtime requires that all resources be allocated from the managed heap. –Managed heap has a pointer NextObjPtr which indicates where the next object is to be allocated within the heap. 45

46 © FPT Software Garbage Collection – Algorithm –The garbage collector checks to see if there are any objects in the heap that are no longer being used by the application. –If such objects exist, then the memory used by these objects can be reclaimed. –If no more memory is available for the heap, then the new operator throws an OutOfMemoryException. 46

47 © FPT Software Garbage Collection – Algorithm –Every application has a set of roots. –Roots identify storage locations, which refer to objects on the managed heap or to objects that are set to null. –The list of active roots is maintained by the just-in- time (JIT) compiler and common language runtime, and is made accessible to the garbage collector's algorithm. 47

48 © FPT Software References Pro C# 5.0 and the.NET 4.5 Framework by Andrew TroelsenPro C# 5.0 and the.NET 4.5 Framework 48

49 © FPT Software Question & Answer 49


Download ppt "© FPT Software Advanced features in C# 1. © FPT Software Agenda Attributes Delegates & Events Anonymous Types & Dynamic Type Extension Methods Lambda."

Similar presentations


Ads by Google