© FPT Software Advanced features in C# 1. © FPT Software Agenda Attributes Delegates & Events...

46
© FPT Software Advanced features in C# 1

Transcript of © FPT Software Advanced features in C# 1. © FPT Software Agenda Attributes Delegates & Events...

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

© FPT Software

Advanced features in C#

1

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

© FPT Software© FPT Software

Agenda

• Attributes• Delegates & Events• Anonymous Types & Dynamic Type• Extension Methods• Lambda Expressions• Reflection• Preprocessor Directives• Garbage Collection• Q&A

2

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

© FPT Software© FPT Software

Agenda

• Attributes• Delegates & Events• Anonymous Types & Dynamic Type• Extension Methods• Lambda Expressions• Reflection• Preprocessor Directives• Garbage Collection• Q&A

3

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

© FPT Software© 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

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

© FPT Software© FPT Software

Attributes

5

Create new DisplayName attribute

Apply DisplayName to add metadata for

enum

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

© FPT Software© 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

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

© FPT Software© FPT Software

Attributes

Attribute Name DescriptionBrowsable Should a property or event be displayed in the

property windowSerializable Allows a class or struct to be serializedObsolete Compiler will complain if target is usedProgId COM Prog IDTransaction Transactional characteristics of a class

7

Some predefined .NET Framework attributes

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

© FPT Software© FPT Software

Agenda

• Attributes• Delegates & Events• Anonymous Types & Dynamic Type• Extension Methods• Lambda Expressions• Reflection• Preprocessor Directives• Garbage Collection• Q&A

8

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

© FPT Software© 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

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

© FPT Software© FPT Software

Agenda

• Attributes• Delegates & Events• Anonymous Types & Dynamic Type• Extension Methods• Lambda Expressions• Reflection• Preprocessor Directives• Garbage Collection• Q&A

13

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

© FPT Software© 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

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

© FPT Software© 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 }

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

© FPT Software© FPT Software

Anonymous Types

16

Create new Anonymous type with two properties

are Color & Price

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

© FPT Software© FPT Software

Dynamic Types

17

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);

ScriptObject calc = GetCalculator();object res = calc.Invoke("Add", 10, 20);int sum = Convert.ToInt32(res);

dynamic calc = GetCalculator();int sum = calc.Add(10, 20);

Statically typed to be dynamic

Dynamic method invocation

Dynamic conversion

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

© FPT Software© 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<int> { 1, 2, 3 };

Compile-time typedynamic

Run-time typeSystem.Int32

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

© FPT Software© 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); ...}

double x = 1.75;double 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);

Method chosen at run-time: int Abs(int x)

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

© FPT Software© FPT Software

Agenda

• Attributes• Delegates & Events• Anonymous Types & Dynamic Type• Extension Methods• Lambda Expressions• Reflection• Preprocessor Directives• Garbage Collection• Q&A

20

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

© FPT Software© 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

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

© FPT Software© FPT Software

Extension Methods

22

Create new Extension method

ConvertToNumber for string type

Use ConvertToNumber method to convert string

to int

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

© FPT Software© FPT Software

Agenda

• Attributes• Delegates & Events• Anonymous Types & Dynamic Type• Extension Methods• Lambda Expressions• Reflection• Preprocessor Directives• Garbage Collection• Q&A

23

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

© FPT Software© 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

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

© FPT Software© FPT Software

Lambda Expressions

• Many Standard query operators have an input parameter whose type is one of the Func<T, TResult> family of generic delegates

• These delegates use type parameters to define the number and types of input parameters, and the return type of the delegate.

25

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

© FPT Software© FPT Software

Agenda

• Attributes• Delegates & Events• Anonymous Types & Dynamic Type• Extension Methods• Lambda Expressions• Reflection• Preprocessor Directives• Garbage Collection• Q&A

26

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

© FPT Software© 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

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

© FPT Software© 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

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

© FPT Software© 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

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

© FPT Software© 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

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

© FPT Software© 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

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

© FPT Software© 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

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

© FPT Software© FPT Software

Reflection - Example

33

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

© FPT Software© 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

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

© FPT Software© 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

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

© FPT Software© 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

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

© FPT Software© FPT Software

Agenda

• Attributes• Delegates & Events• Anonymous Types & Dynamic Type• Extension Methods• Lambda Expressions• Reflection• Preprocessor Directives• Garbage Collection• Q&A

37

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

© FPT Software© 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

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

© FPT Software© FPT Software

Preprocessor Directives

Directive Description

#define, #undef Define and undefine conditional symbols

#if, #elif, #else, #endif Conditionally skip sections of code

#error, #warning Issue errors and warnings

#region, #end Delimit outline regions

#line Specify line number

39

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

© FPT Software© FPT Software

Preprocessor Directives - Conditional Compilation

40

#define Debugpublic 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”); ... }}

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

© FPT Software© 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

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

© FPT Software© FPT Software

Agenda

• Attributes• Delegates & Events• Anonymous Types & Dynamic Type• Extension Methods• Lambda Expressions• Reflection• Preprocessor Directives• Garbage Collection• Q&A

42

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

© FPT Software© FPT Software

Garbage Collection

– Memory Management technique.

– Process of freeing objects.

– No longer referenced by the program.

43

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

© FPT Software© 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

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

© FPT Software© 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

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

© FPT Software© 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

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

© FPT Software© 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

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

© FPT Software© FPT Software

References

• Pro C# 5.0 and the .NET 4.5 Framework by Andrew Troelsen

48

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

© FPT Software© FPT Software

Question & Answer

49