Chengyu Sun California State University, Los Angeles CS4540 Special Topics in Web Development C# for Java Programmers: Advanced Language Features Chengyu Sun California State University, Los Angeles
Overview Indexers Extension methods Delegates Anonymous methods Lambda expressions event
Access List Elements By Index List<string> translations = …. for( int i=0 ; i < translations.Count ; ++i ) Console.WriteLine("{0}. {1}", i+1, transactions[i]); List elements can be accessed like array elements Where does it say this in the List API documentation??
Indexer Syntax public T this[int index] { get; set; } A type parameter for a generic collection, or a regular type for a non-generic one
About Indexer It's a property backed by a getter and/or a setter The type of index doesn't have to be int Internally the index property has a name which can be used by other languages Default name Item Can be customized with an IndexerName attribute Some classes that have indexers: List, Dictionary, String
Add Methods To A Class Example: add a method Substring(string a, string b) to String which returns the substring that starts with a and ends with b, e.g. "Amazon".Substring("a","z") "Amaz" How can we do this when String is a sealed class (like a final class in Java) which can not be in inherited
An Extension Method public static class MyExtensions { public static string Substring( this string s, string begin, string end) { … } } var word = "Amazon"; Console.WriteLine( word.Substring("a", "z") );
About Extension Methods Static methods invoked using instance method syntax Must be defined in a non-generic, static class Use with caution – static, utility methods are not replacements for proper OO design & implementation
The Need for Function (or Method) References GUI programming E.g. button click Asynchronous programming E.g. Ajax request Some object has a field/property that is of function type The field/property is assigned a function (a.k.a. event handler or callback function) The function will be called when something happens
Function References in Some Language C and C++ have function pointers In JavaScript, functions are objects (i.e. no special treatment needed) What's about Java? No function references Use objects that implement certain interfaces (e.g. ActionListener) event handler/callback function must have a certain name (in addition to parameters and return types)
A C# Delegate // Define a delegate type that represents references to // methods with a particular parameter list and return type public delegate int BinaryOp(int op1, int op2); // A method static int Add(int a, int b) => a + b; // Create a delegate object that references the method BinaryOp bop = new BinaryOp(Program.Add); // Call the method int sum = bop(10, 20);
Multicast C# delegates support multicast, i.e. references multiple methods and invoke them together int Add2(int x, int y) => x + y; bop += (new Program()).Add2; Overloaded += operator that adds a method to the list of methods referenced by the delegate
Simplify Use of Delegates Generic delegates for methods take up to 16 arguments Action<> for methods that return void Func<> for methods that return a value Method group conversion allows providing a method in place of a delegate
Anonymous Method Can access variables outside the method int c = 100; BinaryOp bop = delegate(int a, int b) { return a+b+c; }; Must have a ; after the method body
Lambda Expression (parameter list) => { statements; } The simpler and preferred way to write anonymous methods, e.g. int c = 100; BinaryOp bop = (int a, int b) => { return a+b+c; };
Syntactical Variations of Lambda Expression Action<> line = () => { Console.WriteLine(); }; () => Console.WriteLine(); Func<int,int> square = (int x) => { return x*x; }; (int x) => x*x; (x) => x*x; x => x*x;
Closure Example in JavaScript function foo(){ let value=10; return () => {console.log(value++);} } var bar1 = foo(); var bar2 = foo(); bar1(); // ?? bar2(); // ??
Closure in C# Like functions in JavaScript, anonymous methods and lambda expression in C# form closures, i.e. the combination of a function and the lexical environment within which that function was declared Example??
Delegate Example: List.FindAll() Use List.FindAll() to find all the people whose last name is Doe
Event Handling Example Register two event handlers for the text entered event of MockTextField 1. Using regular delegate The event handlers object must be private to prevent client code messing it up 2. Using event The compiler automatically provides registration and unregistration methods and guard against undesirable actions
Readings Pro C# 7: Chapter 10, 11