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

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

Attributes Programming in C# Attributes CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis.
CS 4800 By Brandon Andrews.  Specifications  Goals  Applications  Design Steps  Testing.
Road Map Introduction to object oriented programming. Classes
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++
Advanced Object-Oriented Programming Features
What’s New in C# 4.0? Pavel Yosifovich SELA Group
C# Programming: From Problem Analysis to Program Design1 Advanced Object-Oriented Programming Features C# Programming: From Problem Analysis to Program.
ASP.NET Programming with C# and SQL Server First Edition
Reflection, Conversions, and Exceptions Tom Roeder CS fa.
C++ fundamentals.
Gurinder CTO. Lisa Feigenbaum Microsoft Program Manager Visual Studio Languages
From C++ to C#. Web programming The course is on web programming using ASP.Net and C# The course is on web programming using ASP.Net and C# ASP.Net is.
demo video demo Dynamic Languages Simple and succinctImplicitly typedMeta-programmingNo compilation Static Languages RobustPerformantIntelligent.
Differences between C# and C++ Dr. Catherine Stringfellow Dr. Stewart Carpenter.
OOP Languages: Java vs C++
A First Program Using C#
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Programming Languages and Paradigms Object-Oriented Programming.
Introduction to .Net Framework
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
BIM313 – Advanced Programming Techniques Object-Oriented Programming 1.
Kalpesh Padia Reflection in.Net. OVERVIEW 9/19/
Reflection in.Net Siun-Wai Seow. Objective Explain.NET Reflection When to use it? How to use it? Topic is in the final exam.
C# Programming Fundamentals of Object-Oriented Programming Fundamentals of Object-Oriented Programming Introducing Microsoft.NET Introducing Microsoft.NET.
Java Implementation: Part 3 Software Construction Lecture 8.
Introduction to C# C# is - elegant, type-safe, object oriented language enabling to build applications that run on the.NET framework - types of applications.
All types in the CLR are self-describing – CLR provides a reader and writer for type definitions System.Reflection & System.Reflection.emit – You can ‘read’
Calculator calc = GetCalculator(); int sum = calc.Add(10, 20); Calculator calc = GetCalculator(); int sum = calc.Add(10, 20); object calc.
Reflection Leveraging the Power of Metadata. Objectives Provide an introduction to.NET Reflection Explain how applications can use Reflection to explore.
ABHISHEK BISWAS.NET Reflection Dynamically Create, Find and Invoke Types.
E FFECTIVE C# 50 Specific Ways to Improve Your C# Second Edition Bill Wagner محمد حسین سلطانی.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
C# EMILEE KING. HISTORY OF C# In the late 1990’s Microsoft recognized the need to be able to develop applications that can run on multiple operating system.
Object Oriented Software Development
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Bill Campbell, UMB Microsoft's.NET C# and The Common Language Runtime.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
 Objects versus Class  Three main concepts of OOP ◦ Encapsulation ◦ Inheritance ◦ Polymorphism  Method ◦ Parameterized ◦ Value-Returning.
Introduction to Object-Oriented Programming Lesson 2.
Object Oriented Software Development 4. C# data types, objects and references.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
.NET Mobile Application Development XML Web Services.
Introduction to C# Anders Hejlsberg Distinguished Engineer Developer Division Microsoft Corporation.
1 C# - Inheritance and Polymorphism. 2 1.Inheritance 2.Implementing Inheritance in C# 3.Constructor calls in Inheritance 4.Protected Access Modifier 5.The.
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 –
Internet Computing Module II. Syllabus Creating & Using classes in Java – Methods and Classes – Inheritance – Super Class – Method Overriding – Packages.
.Net Reflection Taipan Tamsare. Overview Reflection core concepts Exploring metadata Detail information Attributes Building Types at runtime.
Luke Hoban Senior Program Manager Microsoft Session Code: DTL310.
© Copyright SELA software & Education Labs Ltd Baruch Hirsch St.Bnei Brak Israel 1 בס " ד.
METADATA IN.NET Presented By Sukumar Manduva. INTRODUCTION  What is Metadata ? Metadata is a binary information which contains the complete description.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming I 7 th Lecture Pavel Ježek
Visual Studio 2010 and.NET Framework 4 Training Workshop.
INTRODUCTION BEGINNING C#. C# AND THE.NET RUNTIME AND LIBRARIES The C# compiler compiles and convert C# programs. NET Common Language Runtime (CLR) executes.
C# for C++ Programmers 1.
Static data members Constructors and Destructors
Java Primer 1: Types, Classes and Operators
Advanced .NET Programming I 7th Lecture
Microsoft .NET 3. Language Innovations Pan Wuming 2017.
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.
Structs.
Functional Programming with Java
.NET and .NET Core 5.2 Type Operations Pan Wuming 2016.
6 Delegate and Lambda Expressions
Java Programming Language
.NET and .NET Core 10. Enabling Contracts Pan Wuming 2017.
Advanced .NET Programming I 8th Lecture
Presentation transcript:

© FPT Software Advanced features in C# 1

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

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

© 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

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

© 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

© 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

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

© 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

© 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 – message has arrived –A web session has begun 10

© 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

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

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

© 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

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

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

© 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

© 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

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

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

© 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

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

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

© 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

© 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

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

© 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

© 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

© 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 29

© 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

© 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

© 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

© FPT Software Reflection - Example 33

© 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

© 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

© 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

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

© 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

© 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

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

© 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

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

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

© 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

© 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

© 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

© 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

© 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

© FPT Software Question & Answer 49