Extension Methods Programming in C# Extension Methods CSE 459.24 Prof. Roger Crawfis.

Slides:



Advertisements
Similar presentations
The Microsoft Technical Roadshow 2007 Language Enhancements and LINQ Daniel Moth Developer & Platform Group Microsoft Ltd
Advertisements

Optional Static Typing Guido van Rossum (with Paul Prescod, Greg Stein, and the types-SIG)
LINQ and Collections An introduction to LINQ and Collections.
Extension Methods, Anonymous Types LINQ Query Keywords, Lambda Expressions Svetlin Nakov Telerik Corporation
Copyright © 2012 Pearson Education, Inc. Chapter 9 Delegates and Events.
.NET 3.5 – Mysteries. NetFx Evolution NetFx 1.0 C# 1.0, VB 7.0, VS.NET NetFx 1.1 C# 1.1, VB 7.1, VS 2003 NetFx 2.0 C# 2.0, VB 8.0, VS 2005 NetFx 3.0 C#
C# and LINQ Yuan Yu Microsoft Research Silicon Valley.
Delegates and lambda functions Jim Warren, COMPSCI 280 S Enterprise Software Development.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 14 th Lecture Pavel Ježek
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# 3.0 Tom Roeder CS fa. Version 3 From PDC 2005 preview compiler available LINQ: language-integrated query High level points: adds native query.
Writing Object Oriented Software with C#. C# and OOP C# is designed for the.NET Framework  The.NET Framework is Object Oriented In C#  Your access to.
2.3 Cool features in C# academy.zariba.com 1. Lecture Content 1.Extension Methods 2.Anonymous Types 3.Delegates 4.Action and Func 5.Events 6.Lambda Expressions.
Delegates and Events Tom Roeder CS fa. Motivation – Function Pointers Treat functions as first-class objects eg. Scheme: (map myfunc somelist)
Cs164 Prof. Bodik, Fall Symbol Tables and Static Checks Lecture 14.
Programming Concepts MIT - AITI. Variables l A variable is a name associated with a piece of data l Variables allow you to store and manipulate data in.
PARALLEL PROGRAMMING ABSTRACTIONS 6/16/2010 Parallel Programming Abstractions 1.
Differences between C# and C++ Dr. Catherine Stringfellow Dr. Stewart Carpenter.
C# vs. C++ What's Different & What's New. An example C# public sometype myfn { get; set; } C++ public: sometype myfn { sometype get (); void set (sometype.
LINQ Programming in C# LINQ CSE Prof. Roger Crawfis.
1. 2 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Decisions { class.
CSE 331 Software Design & Implementation Hal Perkins Autumn 2012 Java Classes, Interfaces, and Types 1.
Eric Vogel Software Developer A.J. Boggs & Company.
Advanced .NET Programming I 13th Lecture
Methods (Functions) CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Karel J Robot An introduction to BlueJ and Object- Oriented Programming.
Lambdas and Streams. Functional interfaces Functional interfaces are also known as single abstract method (SAM) interfaces. Package java.util.function.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# 3.0 and.NET 3.5: A Brief Overview Pavel Ježek.
Delegates and lambda functions Jim Warren, COMPSCI 280 S Enterprise Software Development.
Putting it all together: LINQ as an Example. The Problem: SQL in Code Programs often connect to database servers. Database servers only “speak” SQL. Programs.
Extension Methods, Anonymous Types LINQ Query Keywords, Lambda Expressions Based on material from Telerik Corporation.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Class Example - Rationals Rational numbers are represented by the ratio of two integers, a numerator and a denominator, e.g., 2/3. This is opposed to irrational.
Delegates Programming in C# Delegates CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis.
Session 08 Module 14: Generics and Iterator Module 15: Anonymous & partial class & Nullable type.
ILM Proprietary and Confidential -
Hoang Anh Viet Hà Nội University of Technology Chapter 1. Introduction to C# Programming.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Introduction to C#. Why C#? Develop on the Following Platforms ASP.NET Native Windows Windows 8 / 8.1 Windows Phone WPF Android (Xamarin) iOS (Xamarin)
C# 2.0 and Future Directions Anders Hejlsberg Technical Fellow Microsoft Corporation.
Lambda Expressions Version 1.0
C#.Net Software Development Versions 1.0. Overview  Rational for Extension Methods  C# Specification for Extension Methods  Requirements for Extension.
C#: Future Directions in Language Innovation Anders Hejlsberg TLN307 Technical Fellow Microsoft Corporation.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming I 10 th Lecture Pavel Ježek
Inside LINQ to Objects How LINQ to Objects work Inside LINQ1.
Introduction to C# 2.0 An Advanced Look Adam Calderon Principal Engineer - Interknowlogy Microsoft MVP – C#
PROGRAMMING IN C#. Collection Classes (C# Programming Guide) The.NET Framework provides specialized classes for data storage and retrieval. These classes.
Generics Generics vs. heterogeneous collections Doing your own generics FEN 2014UCN Teknologi/act2learn1.
Satisfy Your Technical Curiosity C# 3.0 Raj Pai Group Program Manager Microsoft Corporation
IAP C# 2011 Lecture 2: Delegates, Lambdas, LINQ Geza Kovacs.
Arrays & Enum & Events. Arrays Arrays are data structures consisting of related data items of the same type. Arrays are fixed-length entities—they remain.
LINQ and Lambda Expressions Telerik Software Academy LINQ Overview.
Chapter  Array-like data structures  ArrayList  Queue  Stack  Hashtable  SortedList  Offer programming convenience for specific access.
Methods. The Structure of a Method Essentially, a method is a block of code with a name. You can execute the code by using the method’s name. You can.
1 New Features in C# 2.0 Generic Types Iterators Simplified Delegates Anonymous Methods Partial Types Various © University of Linz, Institute for System.
Functional Programming Data Aggregation and Nested Queries Ivan Yonkov Technical Trainer Software University
The need for Programming Languages
C# for C++ Programmers 1.
Classes (Part 1) Lecture 3
Advanced .NET Programming I 3nd Lecture
Lambda Expressions By Val Feldsher.
Advanced .NET Programming I 4th Lecture
Namespaces, Scopes, Access privileges
LINQ - 2 Ravi Kumar C++/C# Team.
Advanced .NET Programming I 5th Lecture
Advanced .NET Programming I 4th Lecture
Advanced .NET Programming I 6th Lecture
Corresponds with Chapter 5
Chengyu Sun California State University, Los Angeles
Presentation transcript:

Extension Methods Programming in C# Extension Methods CSE Prof. Roger Crawfis

Extension Methods Can add methods to other classes Let me repeat that: Can add methods to other classes any methods (although they look static) only from static classes When you import a namespace that has extensions, these are added to classes once imported, called as usual instance methods Local methods take precedence

Extension Methods public static class Extensions { public static int ToInt32(this string integerString) { return Int32.Parse(integerString); } public static T[] Slice (this T[] source, int startIndex, int count) { if (startIndex < 0 || count < 0 || (source.Length - startIndex) < count) throw new InvalidArgumentException(); T[] result = new T[count]; Array.Copy(source, startIndex, result, 0, count); return result; }

Extension Methods Properties, events and operators can not have extension methods. Equivalent to calling the static method Can only access public methods, etc. Allows for chaining method calls. More later when we talk about LINQ.

Extension Method Example public static class MyExtensions { public static IEnumerable SkipLast (this IEnumerable source, int count) { Queue saveList = new Queue (); int saved = 0; foreach (T item in source) { if (saved < count) { saveList.Enqueue(item); ++saved; continue; } saveList.Enqueue(item); yield return saveList.Dequeue(); } yield break; }

Extension Method Example class Program { static void Main(string[] args) { int[] a = new[] { 1, 2, 3, 4, 5 }; var b = a.SkipLast(2); foreach (var item in b) Console.WriteLine(item); var c = new List () { "one", "two", "three", "four", "five" }; var d = c.Skip(1).SkipLast(1); foreach (var e in d) Console.WriteLine(e); } two three four two three four

Extension Methods Programming in C# Extension Methods CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis

Types - Misc Programming in C# Types - Misc CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis

Initializers We already know how to initialize basic types: int index = 0; string message = “Save the Cheerleader”; And complex types using constructors: Person paul = new Person(“Paul”, “Newman”); IList words = new List (35); Can also use initializers to set properties and initialize collections.

Initializers Can initialize fields or properties. new C(1, 2) {Name=“my class”}; Works if public field or a property with public set Point a = new Point { X = 0, Y = 1 }; Can be nested (eg. Rectangle with two Points) Collection initializers List digits = new List { 0, 1}; Must implement System.Generic.ICollection

Initializers Example public class Student{ public string firstName; public string lastName; } public class ScienceClass{ public Student Student1, Student2, Student3; } static void Main(string[] args){ var student1 = new Student { firstName = "Bruce", lastName = "Willis“ }; var student2 = new Student { firstName = "George", lastName = "Clooney"}; var student3 = new Student { firstName = "James", lastName = "Cameron“ }; var sClass = new ScienceClass { Student1 = student1, Student2 = student2, Student3 = student3 }; }

Initializers Example // Using a Constructor Person p = new Person("John", "Doe", " "); // Using Properties and an initializer Person p = new Person() { FirstName="John", LastName="Doe", Phone=" ", City="Phoenix"}; // Adding a composite type Person p = new Person() { FirstName = "John", LastName = "Doe", Address = new Address() { Street = "1234 St.", City = "Phoenix“ } };

Implicitly Typed Variables Type of the variable induced from expression Must include an initializer Can not be null. var i = 5; var s = "Hello"; var d = 1.0; // Did you really mean a double? var orders = new Dictionary (); var a = new Point { X = 0, Y = 1 };

Implicitly Typed Variables Implicitly typed arrays var a = new[ ] { 1, 10, 100, 1000 }; Must have consistent types or have implicit conversions

Anonymous Types var x = new {p1 = 10, p2 = “name”}; x is an anonymous type An anonymous type can not be referred to by name in a program. Structural type equivalence Two anonymous types can be compatible Why in the world would we want these? Again, needed/useful for LINQ.

Anonymous Types Example protected object AnonymousTypes() { // *** Create Complex Types 'on the fly‘ var Customer = new { Company = "West Wind", Name = "Rick", Entered = DateTime.Now, BillRate = 150M, Contacts = new { Phone = " ", Fax = " ", = } }; return Customer; }

Types - Misc Programming in C# Types - Misc CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis

Anonymous Methods Programming in C# Anonymous Methods CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis

Anonymous Method Example Becomes quite cumbersome to create little methods for each specialization. These methods are only used in one context. The use and declaration are disjoint. Would be nice to have the declaration in-line. personList.RemoveAll( delegate(Person person) { return person.DateOfBirth.Year < 1980; });

Anonymous Methods Delegates are clumsy: programmer has to name the function and “closure-convert” by hand C# 2.0 introduced anonymous methods No name Compiler does closure-conversion, creating a class and object that captures the environment e.g. bool b = xs.Exists(delegate(int x) { return x > y; }); Local y is free in body of anonymous method

Anonymous Methods Further simplification Button button = new Button(); Button.Click += delegate (object sender, EventArgs arg) { Console.WriteLine("clicked"); }; Can be simplified as follows Button.Click += delegate { Console.WriteLine("clicked"); }; Formal parameters can be omitted if they are not used in the method body delegate void EventHandler (object sender, EventArgs arg);

Outer Variables If anonymous methods access variables of the enclosing method, these variables are evacuated into a dummy object (capturing) The anonymous method and the enclosing method itself are then using a single evacuated variable delegate int Adder(); static Adder CreateAdder() { int x = 0; return delegate { x++; return x; }; } public static void Main() { Adder add = CreateAdder(); Console.WriteLine(add()); add = CreateAdder(); Console.WriteLine(add()); } Output: x++; return x; 0 dummy object delegate add 123 The dummy object lives as long as the delegate object

Anonymous Method Example delegate void MyDelegate(); class Program { static MyDelegate Foo() { int x = 1; Console.WriteLine("Foo: x = {0}", x); MyDelegate d = delegate { x++; Console.WriteLine("delegate: x = {0}", x); }; d(); d(); Console.WriteLine("Foo: x = {0}", x); MyDelegate d2 = delegate { x += 10; Console.WriteLine("second delegate: x = {0}", x); }; d2(); d(); Console.WriteLine("Foo: x = {0}", x); return d2; } --- Main: Foo()(); Foo: x = 1 delegate: x = 2 delegate: x = 3 Foo: x = 3 second delegate: x = 13 delegate: x = 14 Foo: x = 14 second delegate: x = Main: Foo()(); Foo: x = 1 delegate: x = 2 delegate: x = 3 Foo: x = 3 second delegate: x = 13 delegate: x = 14 Foo: x = 14 second delegate: x = 24 static void Main(string[] args) { Console.WriteLine("--- Main: Foo()();"); Foo()(); Console.WriteLine("--- Main: Foo()();"); Foo()(); } static void Main(string[] args) { Console.WriteLine("--- Main: Foo()();"); Foo()(); Console.WriteLine("--- Main: Foo()();"); Foo()(); } }

Anonymous Methods Programming in C# Anonymous Methods CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis

Lambda Expressions Programming in C# Lambda Expressions CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis

Lambda Expressions Generalized function syntax x. x + 1 in C# 3.0, have x => x + 1 From anonymous delegate syntax: delegate(int x) { return x + 1;} Can have implicitly typed variables Can have more than one variable Can have expression or statement body

Lambda Expressions Expression or statement body Implicitly or explicitly typed parameters Examples: x => x + 1 // Implicitly typed, expression body x => { return x + 1; } // Implicitly typed, statement body (int x) => x + 1 // Explicitly typed, expression body (int x) => { return x + 1; } // Explicitly typed, statement body (x, y) => x * y // Multiple parameters () => Console.WriteLine() // No parameters personList.RemoveAll(p => p.DateOfBirth.Year < 1980);

Lambda Expressions Lambda expressions participate in inference process of type arguments of generic methods In initial phase, nothing is inferred from arguments that are lambda expressions Following the initial phase, additional inferences are made from lambda expressions using an iterative process

Lambda Expressions Type inference public static IEnumerable Select ( this IEnumerable source, Func selector) { foreach (T element in source) yield return selector(element); } If call Select(customers, c => c.Name); T, S mapped to appropriate types

Lambda Expressions Generic extension method example: Calling extension method with lambda expression: List customers = GetCustomerList(); IEnumerable names = customers.Select(c => c.Name); Rewriting extension method call: IEnumerable names = Sequence.Select (customers, c => c.Name); T type argument is inferred to Customer based on source argument type Sequence.Select (customers, c => c.Name) c lambda expression argument type is inferred to Customer Sequence.Select (customers, (Customer c) => c.Name) S type argument is inferred to string based on return value type of the lambda expression Sequence.Select (customers, (Customer c) => c.Name) public static class Sequence { public static IEnumerable Select (this IEnumerable source, Func selector) { foreach (T element in source) yield return selector(element); } } public static class Sequence { public static IEnumerable Select (this IEnumerable source, Func selector) { foreach (T element in source) yield return selector(element); } }

Lambda Expressions A lambda expression is a value, that does not have a type but can be implicitly converted to a compatible delegate type delegate R Func (A arg); Func f1 = x => x + 1; Func f2 = x => x + 1; Func f3 = x => x + 1; // Error double -> int

Lambda Expressions Given the code delegate R Func (A arg); static Z F (X x, Func f1, Func f2) { return f2(f1(x)); } What does the following produce? F("1:15:30", s => TimeSpan.Parse(s), t => t.TotalSeconds)

Extension Methods, … Try this at home! Let’s wrap this discussion up by combining extension methods, implicit types, anonymous types and lambda expressions to create a complex process chain: var processes = System.Diagnostics.Process.GetProcesses()System.Diagnostics.Process.GetProcesses.Where(proc => proc.WorkingSet64 > 20 * 1024 * 1024).OrderByDescending(proc => proc.WorkingSet64).Select(proc => new { Identifier = proc.Id, Name = proc.ProcessName }); foreach (var process in processes) Console.WriteLine("Identifier = {0}, Name = {1}", process.Identifier, process.Name); foreach (var process in processes) Console.WriteLine("Identifier = {0}, Name = {1}", process.Identifier, process.Name);

Lambda Expressions Programming in C# Lambda Expressions CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis