This document discusses delegates, lambda expressions, and events in C#. It covers:
- Delegates allow methods to be passed as arguments or returned as the value of functions.
- Lambda expressions provide a concise way to write inline anonymous methods for use with delegates.
- Events use delegates to allow classes to notify listeners of events, following a publish/subscribe model. Event publisher classes raise events, while listeners subscribe to events.
Generic programming and concepts that should be in C++Anton Kolotaev
The document discusses the concepts and principles of generic programming (GP). Some key points:
- GP aims to develop reusable software libraries by categorizing abstractions into concepts and implementing generic algorithms based on concepts.
- Generic libraries are reusable across user-defined types, composable by operating on types from other libraries, and efficient by having performance on par with hand-coded implementations.
- The generic programming process involves lifting algorithms to higher levels of abstraction through concepts while balancing reusability and efficiency. This allows single generic algorithms to support many concrete types.
Templates in C++ allow functions and classes to operate on different data types in a generic way. Function templates define generic functions that can work on different types, while class templates define generic classes. Templates promote code reuse by defining functions and classes independently of specific types. Function templates and class templates can be overloaded and classes can inherit from class templates.
This document discusses functions in C programming. It defines what a function is and explains why we use functions. There are two types of functions - predefined and user-defined. User-defined functions have elements like function declaration, definition, and call. Functions can pass parameters by value or reference. The document also discusses recursion, library functions, and provides examples of calculating sine series using functions.
1. Functions allow programmers to break programs into smaller, self-contained subprograms, making code more modular and reusable.
2. There are four types of functions: those with no arguments and no return value, no arguments but a return value, arguments but no return value, and arguments with a return value.
3. Functions can be user-defined or library functions provided in standard libraries that perform common tasks like input/output and mathematics. Functions must be declared, defined, and called properly in a program.
Templates allow functions and classes to work with different data types. Template classes define generic class definitions that can be used for multiple types, while template functions define generic functions. When a template is instantiated, actual code is generated for the specific types used. Exceptions provide a mechanism to handle runtime errors in C++ and are used by enclosing code that may throw exceptions in a try block and catching specific exceptions in catch blocks.
1) Functions allow breaking down programs into smaller, self-contained blocks of code that perform specific tasks. Functions make code more organized and reusable.
2) There are two types of functions in C: library functions that are predefined in header files, and user-defined functions that are defined by the user.
3) Functions make code more modular and reusable by allowing the same block of code to be easily called multiple times by name rather than having to rewrite the block.
The document discusses functions in C programming. It defines what a function is and explains why functions are used to avoid duplicating code and make programs easier to design, understand and maintain. It describes the different types of functions like pre-defined and user-defined functions. It also covers function prototypes, parameters, return values, recursion, library functions and pointers.
Generic programming and concepts that should be in C++Anton Kolotaev
The document discusses the concepts and principles of generic programming (GP). Some key points:
- GP aims to develop reusable software libraries by categorizing abstractions into concepts and implementing generic algorithms based on concepts.
- Generic libraries are reusable across user-defined types, composable by operating on types from other libraries, and efficient by having performance on par with hand-coded implementations.
- The generic programming process involves lifting algorithms to higher levels of abstraction through concepts while balancing reusability and efficiency. This allows single generic algorithms to support many concrete types.
Templates in C++ allow functions and classes to operate on different data types in a generic way. Function templates define generic functions that can work on different types, while class templates define generic classes. Templates promote code reuse by defining functions and classes independently of specific types. Function templates and class templates can be overloaded and classes can inherit from class templates.
This document discusses functions in C programming. It defines what a function is and explains why we use functions. There are two types of functions - predefined and user-defined. User-defined functions have elements like function declaration, definition, and call. Functions can pass parameters by value or reference. The document also discusses recursion, library functions, and provides examples of calculating sine series using functions.
1. Functions allow programmers to break programs into smaller, self-contained subprograms, making code more modular and reusable.
2. There are four types of functions: those with no arguments and no return value, no arguments but a return value, arguments but no return value, and arguments with a return value.
3. Functions can be user-defined or library functions provided in standard libraries that perform common tasks like input/output and mathematics. Functions must be declared, defined, and called properly in a program.
Templates allow functions and classes to work with different data types. Template classes define generic class definitions that can be used for multiple types, while template functions define generic functions. When a template is instantiated, actual code is generated for the specific types used. Exceptions provide a mechanism to handle runtime errors in C++ and are used by enclosing code that may throw exceptions in a try block and catching specific exceptions in catch blocks.
1) Functions allow breaking down programs into smaller, self-contained blocks of code that perform specific tasks. Functions make code more organized and reusable.
2) There are two types of functions in C: library functions that are predefined in header files, and user-defined functions that are defined by the user.
3) Functions make code more modular and reusable by allowing the same block of code to be easily called multiple times by name rather than having to rewrite the block.
The document discusses functions in C programming. It defines what a function is and explains why functions are used to avoid duplicating code and make programs easier to design, understand and maintain. It describes the different types of functions like pre-defined and user-defined functions. It also covers function prototypes, parameters, return values, recursion, library functions and pointers.
This document discusses escape sequences, verbatim strings, and substitution markers in C#. It provides examples of using escape sequences like \n for newlines. Verbatim strings prefixed with @ disable escape sequences. Substitution markers like {0} in a format string are replaced with variable values. The document demonstrates various string formatting techniques and taking user input in C# programs.
Operator overloading allows operators like + and - to have different implementations depending on the types of their operands. It allows user-defined types to be manipulated using the same syntax as built-in types. The document discusses various aspects of operator overloading like overloading unary, binary, and stream insertion/extraction operators. It also covers type conversions between basic and user-defined types using constructors and conversion functions. Restrictions on which operators can be overloaded and how different conversion scenarios are handled are explained.
pointers, virtual functions and polymorphisms in c++ || in cppgourav kottawar
The document discusses pointers, virtual functions, and polymorphism in C++. It covers early binding/compile-time polymorphism using function overloading and operator overloading. Late binding/run-time polymorphism is achieved using virtual functions, where the appropriate function version is selected at runtime based on the object. Pointer to objects and using the arrow operator -> to access members through object pointers is described. Memory allocation for single and array objects using new is also covered.
C++: Constructor, Copy Constructor and Assignment operatorJussi Pohjolainen
The document discusses various C++ constructors including default constructors, initialization lists, copy constructors, assignment operators, and destructors. It provides examples of how to properly implement these special member functions to avoid problems like shallow copying and double deletes.
C++11 introduced several new features for functions and lambdas including:
1. Lambda expressions that allow the definition of anonymous inline functions.
2. The std::function wrapper that allows functions and lambdas to be used interchangeably.
3. std::bind that binds arguments to function parameters for creating function objects.
These features improved support for functional programming patterns in C++.
The document provides 20 programming problems and their solutions. Some of the key problems include: writing programs to calculate factorial using recursion, determine if a number is even or odd, swap two numbers using temporary/bitwise operators, find greatest of 3/10 numbers, check if a number is prime/palindromic, and check if a string is a palindrome. The solutions provide sample code snippets and explanations with examples to illustrate the logic.
The document discusses pointers in C programming. It begins by explaining how variables are stored in memory with addresses and values. It then introduces pointers as variables that store memory addresses. Examples are given to demonstrate declaring pointer variables and accessing the value at a pointer's address using the dereference operator (*). The document also covers double pointers and passing arguments by value versus by reference. Key topics covered in less than 3 sentences include: pointers store memory addresses, dereferencing a pointer accesses the value at its address, double pointers point to other pointer variables, call by reference passes argument addresses allowing the called function to modify the original variables.
Implicit conversions and parameters allow interoperability between types in Scala. Implicit conversions define how one type can be converted to another type, and are governed by rules around marking, scope, ambiguity, and precedence. The compiler tries to insert implicit conversions in three places: to match an expected type, to convert a receiver before a method selection, and to provide missing implicit parameters. Debugging implicits involves explicitly writing out conversions to see where errors occur.
Generics allow classes and methods to work with any data type by using substitute parameters for the data types. This delays specifying the actual data type until the class or method is used. The document provides an example of a generic class MyGenericArray that can store and retrieve values of any data type. It also demonstrates a generic method Swap that can swap values of any data type and a generic delegate that handles methods with a type parameter.
The document discusses copy constructors in C++. It explains that a copy constructor is used to initialize an object from another object of the same class. It takes the other object as a reference parameter. The document provides an example class with a copy constructor that copies the member variables of one object to another. It also shows sample code that uses the copy constructor to make a copy of an object.
Virtual functions allow functions in derived classes to override functions in base classes. When a base class pointer points to a derived class object, calling a virtual function through the pointer will call the derived class's version. This allows the same interface to behave differently based on the actual object. Virtual functions are useful for mathematical operations, where a base class defines an interface and derived classes perform specific calculations like addition, subtraction etc. depending on the object type pointed to by the base class pointer.
Templates allow functions and classes to operate on generic types in C++. There are two types of templates: class templates and function templates. Function templates are functions that can operate on generic types, allowing code to be reused for multiple types without rewriting. Template parameters allow types to be passed to templates, similar to how regular parameters pass values. When a class, function or static member is generated from a template, it is called template instantiation.
The document discusses constructors in C++. It explains that constructors allow objects to initialize themselves when they are created by allocating memory. The default constructor is called automatically when an object is created and has the same name as the class with no arguments and no return type. Parameterized constructors can be used to initialize objects with different values by passing arguments. Constructor overloading allows multiple constructors with different parameters. Copy constructors are used to create a new object that is a copy of an existing object. Destructors are used to destroy objects and free allocated memory.
The document discusses several key aspects of programming in C language including:
- C language uses a compiler to translate source code into executable binary code.
- Common elements of a C program include header files, main function, use of printf and scanf functions.
- Basic data types in C include integer, float, character, and other numeric types. Variables of these types can be declared and used in C programs.
Functions in Scala allow dividing programs into smaller, manageable pieces that perform specific tasks. Some key features of functions in Scala include local functions defined inside other functions, first-class functions that can be passed as arguments, partially applied functions, closures that close over variables from outer scopes, and repeated/variable length parameters indicated with an asterisk. Tail recursion makes recursive functions more efficient by ensuring the recursive call is the last operation.
The document discusses functions in C programming. It provides examples of defining functions with parameters and return types, calling functions by passing arguments, using header files to declare functions, and recursion. It shows functions being defined and called to perform tasks like calculating factorials, displaying prices based on hotel rates and nights, and converting numbers to binary. Functions allow breaking programs into smaller, reusable components.
C Programming Language is the most popular computer language and most used programming language till now. It is very simple and elegant language. This lecture series will give you basic concepts of structured programming language with C.
Some key features of Scala include:
1. It allows blending of functional programming and object-oriented programming for more concise and powerful code.
2. The static type system allows for type safety while maintaining expressiveness through type inference, implicits, and other features.
3. Scala code interoperates seamlessly with existing Java code and libraries due to its compatibility with the JVM.
The document summarizes new features introduced in C# 3.0, including local variable type inference, object and collection initializers, anonymous types, auto-implemented properties, extension methods, lambda expressions, LINQ, query expressions, and partial methods. It also provides best practices for using the new features and information on where to find more resources.
This document discusses 10 points to secure ASP.NET MVC applications. It covers securing against security misconfiguration, cross-site request forgery, cross-site scripting attacks, malicious file uploads, sensitive data exposure, SQL injection attacks, and other vulnerabilities. The document provides detailed explanations and code examples for implementing validation, encryption, custom error handling, anti-forgery tokens, input sanitization, and other techniques to protect an MVC application.
This document discusses escape sequences, verbatim strings, and substitution markers in C#. It provides examples of using escape sequences like \n for newlines. Verbatim strings prefixed with @ disable escape sequences. Substitution markers like {0} in a format string are replaced with variable values. The document demonstrates various string formatting techniques and taking user input in C# programs.
Operator overloading allows operators like + and - to have different implementations depending on the types of their operands. It allows user-defined types to be manipulated using the same syntax as built-in types. The document discusses various aspects of operator overloading like overloading unary, binary, and stream insertion/extraction operators. It also covers type conversions between basic and user-defined types using constructors and conversion functions. Restrictions on which operators can be overloaded and how different conversion scenarios are handled are explained.
pointers, virtual functions and polymorphisms in c++ || in cppgourav kottawar
The document discusses pointers, virtual functions, and polymorphism in C++. It covers early binding/compile-time polymorphism using function overloading and operator overloading. Late binding/run-time polymorphism is achieved using virtual functions, where the appropriate function version is selected at runtime based on the object. Pointer to objects and using the arrow operator -> to access members through object pointers is described. Memory allocation for single and array objects using new is also covered.
C++: Constructor, Copy Constructor and Assignment operatorJussi Pohjolainen
The document discusses various C++ constructors including default constructors, initialization lists, copy constructors, assignment operators, and destructors. It provides examples of how to properly implement these special member functions to avoid problems like shallow copying and double deletes.
C++11 introduced several new features for functions and lambdas including:
1. Lambda expressions that allow the definition of anonymous inline functions.
2. The std::function wrapper that allows functions and lambdas to be used interchangeably.
3. std::bind that binds arguments to function parameters for creating function objects.
These features improved support for functional programming patterns in C++.
The document provides 20 programming problems and their solutions. Some of the key problems include: writing programs to calculate factorial using recursion, determine if a number is even or odd, swap two numbers using temporary/bitwise operators, find greatest of 3/10 numbers, check if a number is prime/palindromic, and check if a string is a palindrome. The solutions provide sample code snippets and explanations with examples to illustrate the logic.
The document discusses pointers in C programming. It begins by explaining how variables are stored in memory with addresses and values. It then introduces pointers as variables that store memory addresses. Examples are given to demonstrate declaring pointer variables and accessing the value at a pointer's address using the dereference operator (*). The document also covers double pointers and passing arguments by value versus by reference. Key topics covered in less than 3 sentences include: pointers store memory addresses, dereferencing a pointer accesses the value at its address, double pointers point to other pointer variables, call by reference passes argument addresses allowing the called function to modify the original variables.
Implicit conversions and parameters allow interoperability between types in Scala. Implicit conversions define how one type can be converted to another type, and are governed by rules around marking, scope, ambiguity, and precedence. The compiler tries to insert implicit conversions in three places: to match an expected type, to convert a receiver before a method selection, and to provide missing implicit parameters. Debugging implicits involves explicitly writing out conversions to see where errors occur.
Generics allow classes and methods to work with any data type by using substitute parameters for the data types. This delays specifying the actual data type until the class or method is used. The document provides an example of a generic class MyGenericArray that can store and retrieve values of any data type. It also demonstrates a generic method Swap that can swap values of any data type and a generic delegate that handles methods with a type parameter.
The document discusses copy constructors in C++. It explains that a copy constructor is used to initialize an object from another object of the same class. It takes the other object as a reference parameter. The document provides an example class with a copy constructor that copies the member variables of one object to another. It also shows sample code that uses the copy constructor to make a copy of an object.
Virtual functions allow functions in derived classes to override functions in base classes. When a base class pointer points to a derived class object, calling a virtual function through the pointer will call the derived class's version. This allows the same interface to behave differently based on the actual object. Virtual functions are useful for mathematical operations, where a base class defines an interface and derived classes perform specific calculations like addition, subtraction etc. depending on the object type pointed to by the base class pointer.
Templates allow functions and classes to operate on generic types in C++. There are two types of templates: class templates and function templates. Function templates are functions that can operate on generic types, allowing code to be reused for multiple types without rewriting. Template parameters allow types to be passed to templates, similar to how regular parameters pass values. When a class, function or static member is generated from a template, it is called template instantiation.
The document discusses constructors in C++. It explains that constructors allow objects to initialize themselves when they are created by allocating memory. The default constructor is called automatically when an object is created and has the same name as the class with no arguments and no return type. Parameterized constructors can be used to initialize objects with different values by passing arguments. Constructor overloading allows multiple constructors with different parameters. Copy constructors are used to create a new object that is a copy of an existing object. Destructors are used to destroy objects and free allocated memory.
The document discusses several key aspects of programming in C language including:
- C language uses a compiler to translate source code into executable binary code.
- Common elements of a C program include header files, main function, use of printf and scanf functions.
- Basic data types in C include integer, float, character, and other numeric types. Variables of these types can be declared and used in C programs.
Functions in Scala allow dividing programs into smaller, manageable pieces that perform specific tasks. Some key features of functions in Scala include local functions defined inside other functions, first-class functions that can be passed as arguments, partially applied functions, closures that close over variables from outer scopes, and repeated/variable length parameters indicated with an asterisk. Tail recursion makes recursive functions more efficient by ensuring the recursive call is the last operation.
The document discusses functions in C programming. It provides examples of defining functions with parameters and return types, calling functions by passing arguments, using header files to declare functions, and recursion. It shows functions being defined and called to perform tasks like calculating factorials, displaying prices based on hotel rates and nights, and converting numbers to binary. Functions allow breaking programs into smaller, reusable components.
C Programming Language is the most popular computer language and most used programming language till now. It is very simple and elegant language. This lecture series will give you basic concepts of structured programming language with C.
Some key features of Scala include:
1. It allows blending of functional programming and object-oriented programming for more concise and powerful code.
2. The static type system allows for type safety while maintaining expressiveness through type inference, implicits, and other features.
3. Scala code interoperates seamlessly with existing Java code and libraries due to its compatibility with the JVM.
The document summarizes new features introduced in C# 3.0, including local variable type inference, object and collection initializers, anonymous types, auto-implemented properties, extension methods, lambda expressions, LINQ, query expressions, and partial methods. It also provides best practices for using the new features and information on where to find more resources.
This document discusses 10 points to secure ASP.NET MVC applications. It covers securing against security misconfiguration, cross-site request forgery, cross-site scripting attacks, malicious file uploads, sensitive data exposure, SQL injection attacks, and other vulnerabilities. The document provides detailed explanations and code examples for implementing validation, encryption, custom error handling, anti-forgery tokens, input sanitization, and other techniques to protect an MVC application.
The document discusses various topics related to arrays and tuples in C#, including defining and initializing simple arrays, accessing array elements, multidimensional and jagged arrays, using the Array class, sorting arrays, passing arrays as parameters, enumerations, and tuples. It provides code examples for each topic to demonstrate common usage patterns and best practices for working with arrays and tuples in C#.
C# is a general-purpose, object-oriented programming language intended to be simple and modern. It uses ; and {} similarly to C++ and Java. A basic C# program structure includes namespaces, classes, methods, attributes, and a main method. It supports common data types like integers, floats, booleans, and objects. C# code is compiled to the Common Language Runtime. Key advantages over C++ and Java include more legible code through formalized get/set methods and cleaner event management using delegates.
This document provides an overview of key C# programming concepts such as declaring variables, data types, conditional statements, loops, namespaces, and more. It also discusses topics like initialization and scope of variables, predefined value and reference types, if statements, and using the console for input/output. The goal is to cover basic C# syntax, conventions, and compiler options to get started with programming in C#.
The document summarizes new features in .NET 3.5 including implicitly typed local variables, automatic properties, object and collection initializers, extension methods, lambda expressions, query syntax, and anonymous types. Key features are variables that infer type from initialization value, simplified property declarations, initializing objects and collections in a single statement, extending types without inheritance, lambda functions, LINQ query syntax, and anonymous class types without names.
What is .NET Core?
Tool required for developing .NET Core application.
Understanding Command for using (CLI)
How to create you first Console application and Web Application using Command Line Interface (CLI)
Running ASP.NET Core MVC application using Command Line Interface (CLI)
How to create you first Console application and Web Application using Visual studio 2015
Understanding Project structure of ASP.NET Core MVC
This document discusses delegates, anonymous methods, lambda expressions, and events in C#. Delegates allow encapsulating references to methods and functions. Anonymous methods provide a way to pass code blocks as delegates without needing separate methods. Lambda expressions create anonymous functions using the => operator. Events enable classes to notify other classes when something of interest occurs, with publishers raising events and subscribers handling them.
This document discusses delegates, events, and generic delegates in .NET. It defines delegates as type-safe function pointers that allow methods to be passed as arguments. Delegates are defined using the delegate keyword and can refer to static or instance methods. Events are based on the delegate model and allow classes to notify other classes of occurrences. The EventHandler delegate is commonly used for events without custom data, while EventHandler<TEventArgs> passes custom data. Generic delegates make the parameter type variable, allowing flexibility.
The document discusses how lambdas can be used for various programming patterns and tasks such as mapping and reducing data, creating navigable domain-specific languages, handling events more cleanly, and abstracting common conditional and null checking logic. Lambdas offer a concise syntax for anonymous methods and can be used to make code more readable, refactorable, and maintainable compared to traditional approaches using delegates. Examples are provided for how lambdas can simplify programming patterns around asynchronous execution, expression analysis, reflection, and other tasks.
First part of this presentation explains basics and advantages of using functional programming approaches with lambda calculus.
Second part of this presentation explains how can we use lambda calculus in C# 3.0
Lambda Expressions in C# From Beginner To Expert - Jaliya UdagedaraJaliya Udagedara
This document discusses lambda expressions in C#. It introduces lambda expressions as anonymous inline functions that can be used wherever delegates are required. It covers the evolution of delegates from named methods to anonymous methods to lambda expressions. It also discusses how lambda expressions can be used as generic delegates like Action, Func and Predicate. Finally, it discusses how lambda expressions are executed when called, not when constructed, and how they can be used as callbacks by passing a function as a parameter to another function.
The document discusses C++ functions. It explains that functions allow code to be reused by grouping common operations into reusable blocks of code called functions. Functions have three parts: a prototype that declares the function, a definition that implements it, and calls that execute the function. Functions can take parameters as input and return a value. Grouping common code into well-named functions makes a program more organized and maintainable.
Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05CHOOSE
This document summarizes the key features and benefits of LINQ (Language Integrated Query) in .NET. LINQ provides a unified model for querying different types of data like objects, SQL databases, and XML. It allows writing queries directly in C# and VB code as opposed to separate querying APIs. This improves type safety, refactoring support, and reduces errors. The document provides examples of querying different data sources with and without LINQ to demonstrate the improvements.
The document provides an overview of key concepts in the C# programming language including variables and data types, arrays, conditional logic, loops, methods, parameters, and delegates. It discusses basic syntax, operators, and how to perform common tasks like type conversions and working with dates and strings. The goal is to give readers enough information to get started with C# as well as refer back to for language details while working through ASP.NET examples.
Anonymous types use the keyword var. Var is also used in Pascal and Delphi today, but var in Delphi is like ByRef in Visual Basic (VB) or ref in C#. The var introduced with .NET 3.5 indicates an anonymous type. Now, our VB friends are going to think, “Well, we have had variants for years in VB.” But var is not a dumbing down and clogging up of C#. Anonymous types are something new and necessary.
The document summarizes the new features introduced in C# 3.0 and Visual Studio 2008 (code named "Orcas"). It discusses implicit typing, auto-implemented properties, object and collection initializers, extension methods, anonymous types, lambda expressions, generic delegates, and expression trees. It provides examples for many of these new features and encourages attendees to ask questions.
The document discusses C# delegates and events. It defines a delegate as a class that encapsulates a method signature and can be used to pass methods as parameters. Delegates allow methods to be assigned and invoked dynamically. Events are a special type of delegate used to define callbacks that are invoked when an event occurs. The document provides examples of singlecast and multicast delegates, declaring and using delegates, and creating a custom delegate and event.
C++ templates allow functions and classes to operate on multiple types of data. Templates define placeholders that are substituted by template arguments. This allows defining functions and classes once that can work with different data types. Function templates define a single function that generates multiple versions based on the template arguments. Class templates generate distinct classes from a single definition. Exceptions represent errors and are thrown using throw statements. Exception handlers use try-catch blocks to catch exceptions and provide error handling.
1. MATLAB is a software package for mathematical computation, numerical computation, algorithm development, data analysis, and more. It allows matrix manipulations, plotting of functions and data, implementation of algorithms, creation of user interfaces, and interfacing with programs in other languages.
2. The document introduces basic MATLAB operations like arithmetic operations, variables, matrices, plotting, scripts and functions. It also discusses flow control and logical operations like if/else statements and loops.
3. MATLAB can be used for scientific and engineering applications like modeling, simulation, and prototyping through its implementation of algorithms, data analysis tools, and graphical capabilities for visualizing data.
The document introduces C# as the first component-oriented language in the C/C++ family. It discusses key features of C# including everything being an object, robust and durable software through garbage collection and exceptions, and preservation of investment from C++. It provides examples of basic C# concepts like classes, structs, interfaces, enums, delegates, properties and events.
The document introduces C# as the first component-oriented language in the C/C++ family. It discusses key features of C# including everything being an object, robust and durable software, and preservation of investment from other languages. It provides examples of basic C# syntax and programming structures.
The document introduces C# as the first component-oriented language in the C/C++ family. It discusses key features of C# including everything being an object, robust and durable software, preservation of investment from C++, and providing a unified type system where all types ultimately inherit from object. It provides examples of key C# concepts like classes, structs, interfaces, enums, delegates, properties, events, and attributes.
The document introduces C# as the first component-oriented language in the C/C++ family. It discusses key features of C# including everything being an object, robust and durable software through garbage collection and exceptions, and preservation of investment from C++. It provides examples of basic C# concepts like classes, structs, interfaces, enums, delegates, properties and events.
The document introduces C# as the first component-oriented language in the C/C++ family. It discusses key features of C# including everything being an object, robust and durable software through garbage collection and exceptions, and preservation of investment from C++. It provides examples of basic C# concepts like classes, structs, interfaces, enums, delegates, properties and events.
Similar to Csharp4 delegates lambda_and_events (20)
This document provides an overview of generics in C# including:
- Creating generic classes and interfaces
- Features of generics such as default values, constraints, inheritance, and static members
- Performance and type safety benefits compared to non-generic collections
- Examples of generic methods, covariance/contravariance in generic interfaces, and naming guidelines for generics
This document discusses strings and regular expressions in C#. It covers building and formatting strings, using the StringBuilder class, and examining regular expressions patterns and examples. Regular expressions can be used to perform sophisticated string operations like identifying repeated words or extracting parts of a URI.
The document discusses operators and casts in C#. It covers various types of operators like arithmetic, comparison, conditional, etc. It explains implicit and explicit type conversions between primitive and reference types. It also discusses overloading operators for custom types and implementing user-defined casts.
The document discusses various C# object-oriented programming concepts including classes, structs, class members, passing values by value and reference, method overloading, constructors, static constructors, read-only fields, partial classes, static classes, and the Object class. It provides examples of declaring classes and structs, defining class members like fields, properties, methods, and constructors. It also covers passing parameters, calling constructors from other constructors, readonly fields, and anonymous types.
The document discusses inheritance in C# including implementation inheritance, interface inheritance, abstract classes, sealed classes, constructors, and modifiers. It provides examples of defining base and derived classes, implementing interfaces, overriding and hiding methods, calling base versions of methods, and using access modifiers like public and protected.
The document summarizes new features in C# 4.0 including optional and named parameters, dynamic typing, tuples, complex numbers, parallel programming, and thread-safe data structures. It also mentions code contracts, memory-mapped files, and the Managed Extensibility Framework.
7. BubbleSorter example bool swapped = true; do { swapped = false; for (int i = 0; i < sortArray.Length — 1; i++) { if (sortArray[i] < sortArray[i+1])) // problem with this test { int temp = sortArray[i]; sortArray[i] = sortArray[i + 1]; sortArray[i + 1] = temp; swapped = true; } } } while (swapped); BubbleSorter/BubbleSorter.cs BubbleSorter/Employee.cs BubbleSorter/Program.cs
8. Multicast delegates Action <double> operations = MathOperations.MultiplyByTwo; operations += MathOperations.Square; MulticastDelegates/Program.cs MulticastDelegates/MathOperations.cs MulticastDelegateWithIteration/Program.cs Action < double > operation1 = MathOperations.MultiplyByTwo; Action < double > operation2 = MathOperations.Square; Action < double > operations = operation1 + operation2; //Multicast delegates also recognize the operators – and - = to remove method calls from the delegate.
11. Lambda Expressions Since C# 3.0, you can use a new syntax for assigning code implementation to delegates: Lambda expressions. Lambda expressions can be used whenever you have a delegate parameter type. The previous example using anonymous methods is changed here to use a Lambda expression. LambdaExpressions/Program.cs
13. Variables outside of the lambda expression int someVal = 5; Func < int, int > f = x => x + someVal; someVal = 7; Console.WriteLine(f(3)); // The result here invoking f(3) is 10
14. Variables outside of the lambda expression cont With the Lambda expression x = > x + someVal the compiler creates an anonymous class that has a constructor to pass the outer variable. The constructor depends on how many variables you access from the outside public class AnonymousClass { private int someVal; public AnonymousClass(int someVal) { this.someVal = someVal; } public int AnonymousMethod(int x) { return x + someVal; } }
15. Variables outside of the lambda expression cont Lambda expressions can be used any place where the type is a delegate. Another use of Lambda expressions is when the type is Expression or Expression <T> . Here the compiler creates an expression tree. This feature is discussed in “ Language Integrated Query. ( LINQ ) Lecture”
16. Events Events are based on delegates and offer a publish/subscribe mechanism to delegates. You can find events everywhere across the framework. In Windows applications, the Button class offers the Click event. This type of event is a delegate. A handler method that is invoked when the Click event is fired needs to be defined, with the parameters as defined by the delegate type.
17. Event Publisher EventsSample/CarDealer.cs The delegate EventHandler < TEventArgs > is defi ned as follows: public delegate void EventHandler <TEventArgs> (object sender, TEventArgs e) where TEventArgs: EventArgs
19. Event Publisher cont Before firing the event, it is necessary to check whether the delegate NewCarInfo is not null . If no one subscribed, the delegate is null : public void NewCar(string car) { Console.WriteLine("CarDealer, new car {0}", car); if (NewCarInfo != null ) { NewCarInfo(this, new CarInfoEventArgs(car)); } }
//SimpleDelegate/MathOperations.cs namespace Najah.ILoveCsharp.Delegates { class MathOperations { public static double MultiplyByTwo(double value) { return value * 2; } public static double Square(double value) { return value * value; } } } //SimpleDelegate/Program.cs using System; namespace Najah.ILoveCsharp.Delegates { delegate double DoubleOp(double x); class Program { static void Main() { DoubleOp[] operations = { MathOperations.MultiplyByTwo, MathOperations.Square }; for (int i = 0; i < operations.Length; i++) { Console.WriteLine(&quot;Using operations[{0}]:&quot;, i); ProcessAndDisplayNumber(operations[i], 2.0); ProcessAndDisplayNumber(operations[i], 7.94); ProcessAndDisplayNumber(operations[i], 1.414); Console.WriteLine(); } } static void ProcessAndDisplayNumber(DoubleOp action, double value) { double result = action(value); Console.WriteLine( &quot;Value is {0}, result of operation is {1}&quot;, value, result); } } }
//BubbleSorter/BubbleSorter.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Najah.ILoveCsharp.Delegates { class BubbleSorter { static public void Sort<T>(IList<T> sortArray, Func<T, T, bool> comparison) { bool swapped = true; do { swapped = false; for (int i = 0; i < sortArray.Count - 1; i++) { if (comparison(sortArray[i+1], sortArray[i])) { T temp = sortArray[i]; sortArray[i] = sortArray[i + 1]; sortArray[i + 1] = temp; swapped = true; } } } while (swapped); } } } //BubbleSorter/Employee.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Najah.ILoveCsharp.Delegates { class Employee { public Employee(string name, decimal salary) { this.Name = name; this.Salary = salary; } public string Name { get; private set; } public decimal Salary { get; private set; } public override string ToString() { return string.Format(&quot;{0}, {1:C}&quot;, Name, Salary); } public static bool CompareSalary(Employee e1, Employee e2) { return e1.Salary < e2.Salary; } } }
//BubbleSorter/BubbleSorter.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Najah.ILoveCsharp.Delegates { class BubbleSorter { static public void Sort<T>(IList<T> sortArray, Func<T, T, bool> comparison) { bool swapped = true; do { swapped = false; for (int i = 0; i < sortArray.Count - 1; i++) { if (comparison(sortArray[i+1], sortArray[i])) { T temp = sortArray[i]; sortArray[i] = sortArray[i + 1]; sortArray[i + 1] = temp; swapped = true; } } } while (swapped); } } } //BubbleSorter/Employee.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Najah.ILoveCsharp.Delegates { class Employee { public Employee(string name, decimal salary) { this.Name = name; this.Salary = salary; } public string Name { get; private set; } public decimal Salary { get; private set; } public override string ToString() { return string.Format(&quot;{0}, {1:C}&quot;, Name, Salary); } public static bool CompareSalary(Employee e1, Employee e2) { return e1.Salary < e2.Salary; } } } //BubbleSorter/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Najah.ILoveCsharp.Delegates { class Program { static void Main() { Employee[] employees = { new Employee(&quot;Bugs Bunny&quot;, 20000), new Employee(&quot;Elmer Fudd&quot;, 10000), new Employee(&quot;Daffy Duck&quot;, 25000), new Employee(&quot;Wile Coyote&quot;, 1000000.38m), new Employee(&quot;Foghorn Leghorn&quot;, 23000), new Employee(&quot;RoadRunner&quot;, 50000) }; BubbleSorter.Sort(employees, Employee.CompareSalary); foreach (var employee in employees) { Console.WriteLine(employee); } } } }
//MulticastDelegates/Program.cs using System; namespace Najah.ILoveCsharp.Delegates { class Program { static void Main() { Action<double> operations = MathOperations.MultiplyByTwo; operations += MathOperations.Square; ProcessAndDisplayNumber(operations, 2.0); ProcessAndDisplayNumber(operations, 7.94); ProcessAndDisplayNumber(operations, 1.414); Console.WriteLine(); } static void ProcessAndDisplayNumber(Action<double> action, double value) { Console.WriteLine(); Console.WriteLine(&quot;ProcessAndDisplayNumber called with value = {0}&quot;, value); action(value); } } } //MulticastDelegates/MathOperations.cs using System; namespace Najah.ILoveCsharp.Delegates { class MathOperations { public static void MultiplyByTwo(double value) { double result = value * 2; Console.WriteLine(&quot;Multiplying by 2: {0} gives {1}&quot;, value, result); } public static void Square(double value) { double result = value * value; Console.WriteLine(&quot;Squaring: {0} gives {1}&quot;, value, result); } } } //MulticastDelegateWithIteration/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Najah.ILoveCsharp.Delegates { class Program { static void One() { Console.WriteLine(&quot;One&quot;); throw new Exception(&quot;Error in one&quot;); } static void Two() { Console.WriteLine(&quot;Two&quot;); } static void Main() { //Action d1 = One; //d1 += Two; //try //{ // d1(); //} //catch (Exception) //{ // Console.WriteLine(&quot;Exception caught&quot;); //} Action d1 = One; d1 += Two; Delegate[] delegates = d1.GetInvocationList(); foreach (Action d in delegates) { try { d(); } catch (Exception) { Console.WriteLine(&quot;Exception caught&quot;); } } } } }
// EventsSample/CarDealer.cs using System; namespace Najah.ILoveCsharp.Delegates { public class CarInfoEventArgs : EventArgs { public CarInfoEventArgs(string car) { this.Car = car; } public string Car { get; private set; } } public class CarDealer { public event EventHandler<CarInfoEventArgs> NewCarInfo; public void NewCar(string car) { Console.WriteLine(&quot;CarDealer, new car {0}&quot;, car); if (NewCarInfo != null) { NewCarInfo(this, new CarInfoEventArgs(car)); } } } }
//EventsSample/Consumer.cs using System; namespace Najah.ILoveCsharp.Delegates { public class Consumer { private string name; public Consumer(string name) { this.name = name; } public void NewCarIsHere(object sender, CarInfoEventArgs e) { Console.WriteLine(&quot;{0}: car {1} is new&quot;, name, e.Car); } } } //EventsSample/Program.cs namespace Najah.ILoveCsharp.Delegates { class Program { static void Main() { var dealer = new CarDealer(); var michael = new Consumer(&quot;Michael&quot;); dealer.NewCarInfo += michael.NewCarIsHere; dealer.NewCar(&quot;Mercedes&quot;); var nick = new Consumer(&quot;Nick&quot;); dealer.NewCarInfo += nick.NewCarIsHere; dealer.NewCar(&quot;Ferrari&quot;); dealer.NewCarInfo -= michael.NewCarIsHere; dealer.NewCar(&quot;Toyota&quot;); } } }
// WeakEventsSample/WeakCarInfoEventManager.cs using System.Windows; namespace Najah.ILoveCsharp.Delegates { public class WeakCarInfoEventManager : WeakEventManager { public static void AddListener(object source, IWeakEventListener listener) { CurrentManager.ProtectedAddListener(source, listener); } public static void RemoveListener(object source, IWeakEventListener listener) { CurrentManager.ProtectedRemoveListener(source, listener); } public static WeakCarInfoEventManager CurrentManager { get { WeakCarInfoEventManager manager = GetCurrentManager(typeof(WeakCarInfoEventManager)) as WeakCarInfoEventManager; if (manager == null) { manager = new WeakCarInfoEventManager(); SetCurrentManager(typeof(WeakCarInfoEventManager), manager); } return manager; } } protected override void StartListening(object source) { (source as CarDealer).NewCarInfo += CarDealer_NewCarInfo; } void CarDealer_NewCarInfo(object sender, CarInfoEventArgs e) { DeliverEvent(sender, e); } protected override void StopListening(object source) { (source as CarDealer).NewCarInfo -= CarDealer_NewCarInfo; } } } //WeakEventsSample/Consumer.cs using System; using System.Windows; namespace Najah.ILoveCsharp.Delegates { public class Consumer : IWeakEventListener { private string name; public Consumer(string name) { this.name = name; } public void NewCarIsHere(object sender, CarInfoEventArgs e) { Console.WriteLine(&quot;{0}: car {1} is new&quot;, name, e.Car); } bool IWeakEventListener.ReceiveWeakEvent(Type managerType, object sender, EventArgs e) { NewCarIsHere(sender, e as CarInfoEventArgs); return true; } } } //WeakEventsSample/Program.cs namespace Najah.ILoveCsharp.Delegates { class Program { static void Main() { var dealer = new CarDealer(); var michael = new Consumer(&quot;Michael&quot;); WeakCarInfoEventManager.AddListener(dealer, michael); dealer.NewCar(&quot;Mercedes&quot;); var nick = new Consumer(&quot;Nick&quot;); WeakCarInfoEventManager.AddListener(dealer, nick); dealer.NewCar(&quot;Ferrari&quot;); WeakCarInfoEventManager.RemoveListener(dealer, michael); dealer.NewCar(&quot;Toyota&quot;); } } }