The document discusses delegates, events, and extension methods in C#. It explains that delegates allow functions to be passed as parameters and can point to methods. Events use delegates to call subscriber methods when an event is raised. Extension methods extend existing classes with new methods without modifying the original class. The document provides examples of how to use delegates to handle events, attach multiple event handlers, and create anonymous methods. It also demonstrates how to write an extension method to add new functionality to the string class.
Pragmatic Functional Refactoring with Java 8Codemotion
by Raoul-Gabriel Urma - You may be hearing a lot of buzz around functional programming. For example, Java 8 recently introduced new features and APIs inspired from functional ideas such as first-class functions, composition and immutability. In this talk we show how you can refactor your traditional object-oriented Java to using FP features and APIs from Java 8 in a beneficial manner. - How to adapt to requirement changes using first-class functions - How you can enhance code reusability using currying - How you can make your code more robust by favouring immutability over mutability - and more!
SOLID
From Wikipedia, the free encyclopedia
===============================
SOLID Principles :
Single responsibility
Open/closed
Liskov substitution
Interface segregation
Dependency inversion
In object-oriented computer programming, SOLID is a mnemonic acronym for five design principles intended to make software designs more understandable, flexible and maintainable.
Se guardiamo oltre la meccanica, il TDD è una tecnica complessa perché richiede molteplici skill. Da principiante dopo l’implementazione di poche storie ti imbatti nel problema dei test che si rompono ad ogni refactoring, è arrivato il momento di migliorare i propri skill di scrittura dei test. Nel talk analizzeremo la struttura dei test, quali sono le bad smell più comuni e come porvi rimedio.
Pragmatic Functional Refactoring with Java 8Codemotion
by Raoul-Gabriel Urma - You may be hearing a lot of buzz around functional programming. For example, Java 8 recently introduced new features and APIs inspired from functional ideas such as first-class functions, composition and immutability. In this talk we show how you can refactor your traditional object-oriented Java to using FP features and APIs from Java 8 in a beneficial manner. - How to adapt to requirement changes using first-class functions - How you can enhance code reusability using currying - How you can make your code more robust by favouring immutability over mutability - and more!
SOLID
From Wikipedia, the free encyclopedia
===============================
SOLID Principles :
Single responsibility
Open/closed
Liskov substitution
Interface segregation
Dependency inversion
In object-oriented computer programming, SOLID is a mnemonic acronym for five design principles intended to make software designs more understandable, flexible and maintainable.
Se guardiamo oltre la meccanica, il TDD è una tecnica complessa perché richiede molteplici skill. Da principiante dopo l’implementazione di poche storie ti imbatti nel problema dei test che si rompono ad ogni refactoring, è arrivato il momento di migliorare i propri skill di scrittura dei test. Nel talk analizzeremo la struttura dei test, quali sono le bad smell più comuni e come porvi rimedio.
Flying Futures at the same sky can make the sun rise at midnightWiem Zine Elabidine
Template made by Slidesgo
Implementing responsive and high-performance applications is the most obvious challenge that we face in our programming life. It’s interesting to deeply study concurrency and parallelism on the JVM. In this talk you will learn how to describe parallel tasks and the idea behind Futures and the execution context. I will cover the tricky part of concurrency when the concurrent tasks share and use the same resources and how flying Futures in the same sky can make the sun rise at midnight! At the end I will talk about some possible solutions that you can use to reduce your worries about the pitfalls of concurrency.
This presentation explains the difference between concurrency and parallelism, and how could we make parallel computations and how could we design an API for parallel computation following the structure presented in the Functional Programming in Scala book
From object oriented to functional domain modelingCodemotion
"From object oriented to functional domain modeling" by Mario Fusco
Malgrado l'introduzione delle lambda, la gran parte degli sviluppatori Java non è ancora abituata agli idiomi della programmazione funzionale e quindi non è pronta a sfruttare a pieno le potenzialità di Java 8. In particolare non è ancora comune vedere dati e funzioni usate insieme quando si modella un dominio di business. Lo scopo del talk è mostrare come alcuni principi di programmazione funzionale quali l'impiego di oggetti e strutture dati immutabili, l'uso di funzioni senza side-effect e il loro reuso mediante composizione, possono anche essere validi strumenti di domain modelling.
Monadic Comprehensions and Functional Composition with Query ExpressionsChris Eargle
Build monads using the C# language with a C# style, then use the appropriate methods to ensure the LINQ query syntax works with this functional design pattern. After describing monads, we will cut the middleman and apply the same techniques directly to objects and functions to achieve better results with a declarative syntax.
Kotlin Perfomance on Android / Александр Смирнов (Splyt)Ontico
РИТ++ 2017, AppsConf
Зал Касабланка, 6 июня, 14:00
Тезисы:
http://appsconf.ru/2017/abstracts/2816.html
В докладе рассмотрим цену использования Kotlin в Runtime, обсудим варианты, как улучшить картину мира. Смотреть будем с точки зрения производительности, синхронно углубляясь в особенности Android, а также подумаем, как можно использовать получившийся байткод.
В докладе срыв подкапотных оптимизаций, байткод и цифры, которые покажут, насколько сильно вам смогут помочь все указанные оптимизации.
Flying Futures at the same sky can make the sun rise at midnightWiem Zine Elabidine
Template made by Slidesgo
Implementing responsive and high-performance applications is the most obvious challenge that we face in our programming life. It’s interesting to deeply study concurrency and parallelism on the JVM. In this talk you will learn how to describe parallel tasks and the idea behind Futures and the execution context. I will cover the tricky part of concurrency when the concurrent tasks share and use the same resources and how flying Futures in the same sky can make the sun rise at midnight! At the end I will talk about some possible solutions that you can use to reduce your worries about the pitfalls of concurrency.
This presentation explains the difference between concurrency and parallelism, and how could we make parallel computations and how could we design an API for parallel computation following the structure presented in the Functional Programming in Scala book
From object oriented to functional domain modelingCodemotion
"From object oriented to functional domain modeling" by Mario Fusco
Malgrado l'introduzione delle lambda, la gran parte degli sviluppatori Java non è ancora abituata agli idiomi della programmazione funzionale e quindi non è pronta a sfruttare a pieno le potenzialità di Java 8. In particolare non è ancora comune vedere dati e funzioni usate insieme quando si modella un dominio di business. Lo scopo del talk è mostrare come alcuni principi di programmazione funzionale quali l'impiego di oggetti e strutture dati immutabili, l'uso di funzioni senza side-effect e il loro reuso mediante composizione, possono anche essere validi strumenti di domain modelling.
Monadic Comprehensions and Functional Composition with Query ExpressionsChris Eargle
Build monads using the C# language with a C# style, then use the appropriate methods to ensure the LINQ query syntax works with this functional design pattern. After describing monads, we will cut the middleman and apply the same techniques directly to objects and functions to achieve better results with a declarative syntax.
Kotlin Perfomance on Android / Александр Смирнов (Splyt)Ontico
РИТ++ 2017, AppsConf
Зал Касабланка, 6 июня, 14:00
Тезисы:
http://appsconf.ru/2017/abstracts/2816.html
В докладе рассмотрим цену использования Kotlin в Runtime, обсудим варианты, как улучшить картину мира. Смотреть будем с точки зрения производительности, синхронно углубляясь в особенности Android, а также подумаем, как можно использовать получившийся байткод.
В докладе срыв подкапотных оптимизаций, байткод и цифры, которые покажут, насколько сильно вам смогут помочь все указанные оптимизации.
Utilizing Kinect Control for a More Immersive Interaction with 3D EnvironmentMohammad Shaker
Utilizing Kinect Control for a More Immersive Interaction with 3D Environment. Implemented by Saed Haj Ali, Kinda Tarboush and Marah Halawah and Supervised by me, Dr. Noor Shaker and Dr. Ammar Joukhadar.
Short, Matters, Love - Passioneers Event 2015Mohammad Shaker
Short, Matters, Love is a presentation I prepared for freshmen students at the Faculty of Information Technology in Damascus, Syria organised by Passioneers - 2015
This is my project in my third year of studying in the Faculty of Information Technology Engineering in Damascus, Syria, 2011 with Ismaeel Abo Abdalla, Zaher Wanli and Mhd Noor Alhamwi. The project simulates the physics of the car movement with/without Anti Brake-Lock System (ABS), Electronic Stability Program (ESP) and Global Positioning System (GPS) all in realtime.
[Development Simply Put] Events & Delegates In C# - Win Forms ControlsAhmed Tarek Hasan
If you already know about "Events" in .NET applications, then you may need to read this article to have a look on an example on how to use "Events" in creating a Windows Form Control.
This is a C# project . I am expected to create as this image shows. .pdfindiaartz
This is a C# project . I am expected to create as this image shows. If the image isnot clearly
showing , it\'s the Chegg\'s system. Please , if you see it quit long, assist me with the starting and
hinting bulltes point or functions that may simplify. Thannks...
The design of the Calculator form
Operation
· To clear the contents of memory, the user clicks the MC button. To save the value that’s
currently displayed in memory, the user clicks the MS button. To recall the value that’s currently
in memory and display it in the calculator, the user clicks the MR button. And to add the value
that’s currently displayed to the value in memory, the user clicks the M+ button.
· An M is displayed in the box above the MC button whenever the memory contains a value.
· See project 12-1 for additional details.
Specifications
· Create a class named MemoryCalculator that inherits the Calculator class described in
project 12-1. The MemoryCalculator class should add properties and methods as needed to
implement the memory function.
Note:
· MemoryCalculator class design:
Method Description
MemoryStore Stores the calculator’s current value in memory.
MemoryRecall Sets the calculator’s current value to the value stored in memory.
MemoryAdd Adds the calculator’s current value to the value currently stored in
memory.
MemoryClear Clears the current memory value.
Solution
Calculator.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Calculator
{
public class Calculator
{
public decimal currentValue;
private decimal operand1;
public decimal operand2;
private Operator op;
public enum Operator { Addd, Subtract, Multiply, Divide, None };
//Needed to be changed from private to public
public Calculator()
{
this.currentValue = 0;
this.operand1 = 0;
this.operand2 = 0;
this.op = Operator.None;
}
public decimal CurrentValue
{
get { return this.currentValue; }
}
public void Clear()
{
this.currentValue = 0;
this.operand1 = 0;
this.operand2 = 0;
this.op = Operator.None;
}
public void Add(decimal val)
{
this.operand1 = val;
this.currentValue = val;
this.op = Operator.Addd;
}
public void Subtract(decimal val)
{
this.operand1 = val;
this.currentValue = val;
this.op = Operator.Subtract;
}
public void Multiply(decimal val)
{
this.operand1 = val;
this.currentValue = val;
this.op = Operator.Multiply;
}
public void Divide(decimal val)
{
this.operand1 = val;
this.currentValue = val;
this.op = Operator.Divide;
}
public void Equals(decimal val)
{
operand2 = val;
switch (this.op)
{
case Operator.Addd:
currentValue = operand1 + operand2;
break;
case Operator.Subtract:
currentValue = operand1 - operand2;
break;
case Operator.Multiply:
currentValue = operand1 * operand2;
break;
case Operator.Divide:
//Try catch to prevent dividing by zero
try
{
currentValue = operand1 / operand2;
}
catch (DivideByZeroException)
{
MessageBox.Show(\"You cannot divide by zero\", \"Error!\");
}
break;
case Opera.
Pragmatic functional refactoring with java 8 (1)RichardWarburton
You may be hearing a lot of buzz around functional programming. For example, Java 8 recently introduced new features (lambda expressions and method references) and APIs (Streams, Optional and CompletableFutures) inspired from functional ideas such as first-class functions, composition and immutability.
However, what does this mean for my existing codebase?
In this talk we show how you can refactor your traditional object-oriented Java to using FP features and APIs from Java 8 in a beneficial manner.
We will discuss:
* How to adapt to requirement changes using first-class functions
* How you can enhance code reusability using currying
* How you can make your code more robust by favouring immutability over mutability
* How you can design better APIs and reduce unintended null pointer exceptions using an optional data type
You may be hearing a lot of buzz around functional programming. For example, Java 8 recently introduced new features (lambda expressions and method references) and APIs (Streams, Optional and CompletableFutures) inspired from functional ideas such as first-class functions, composition and immutability.
However, what does this mean for my existing codebase?
In this talk we show how you can refactor your traditional object-oriented Java to using FP features and APIs from Java 8 in a beneficial manner.
We will discuss:
- How to adapt to requirement changes using first-class functions
- How you can enhance code reusability using currying
- How you can make your code more robust by favouring immutability over mutability
- How you can design better APIs and reduce unintended null pointer exceptions using an optional data type"
Create the equivalent of a four function calculator. The program should request the user to enter a number, an operator, and another number. carry out the specified arithmetical operation: adding, subtracting, multiplying, or dividing the two numbers. (Using switch statement ).ThesisScientist.com
Refactoring of code for more readable, scalable modules based on The book titled "Refactoring - Improving the Design of Existing Code" written by Martin Fowler
JavaScript Patterns to Cleanup your CodeDan Wahlin
This is a talk I gave at the AngleBrackets / DevIntersection conference in Vegas in April of 2013 covering JavaScript patterns that can be used to structure code and clean it up.
DPC 2019, Amsterdam: Beyond design patterns and principles - writing good OO ...Matthias Noback
Of course, you should read all you can about SOLID, Design patterns, Patterns of Enterprise Application Architecture, etc. Once you have a basic understanding of these topics you still have to write that code though, and write it well too! What is good code? Are there some guidelines, or rules of thumb, which you can follow while making your everyday coding decisions?
In this talk I’ll cover many of these coding guidelines, which aren’t usually covered by patterns or principles books. They should help you write better code and give you a richer vocabulary for reviewing other people’s code. Some of the subjects that we’ll discuss are: state, mutability, CQS, one-method objects, domain-first, API-driven, functional programming influences, object boundaries, (de)serialization, and many more!
Ultra Fast, Cross Genre, Procedural Content Generation in Games [Master Thesis]Mohammad Shaker
In my MSc. thesis, I have re-tackled the problem of procedurally generating content for physics-based games I have previously investigated in my BSc. graduation thesis. This time around I propose two novel methods: the first is projection based for faster generation of physics-based games content. The other, The Progressive Generation, is a generic, wide-range, across genre, customisable with playability check method all bundled in a fast progressive approach. This new method is applied on two completely different games: NEXT And Cut the Rope.
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTier1 app
Even though at surface level ‘java.lang.OutOfMemoryError’ appears as one single error; underlyingly there are 9 types of OutOfMemoryError. Each type of OutOfMemoryError has different causes, diagnosis approaches and solutions. This session equips you with the knowledge, tools, and techniques needed to troubleshoot and conquer OutOfMemoryError in all its forms, ensuring smoother, more efficient Java applications.
Accelerate Enterprise Software Engineering with PlatformlessWSO2
Key takeaways:
Challenges of building platforms and the benefits of platformless.
Key principles of platformless, including API-first, cloud-native middleware, platform engineering, and developer experience.
How Choreo enables the platformless experience.
How key concepts like application architecture, domain-driven design, zero trust, and cell-based architecture are inherently a part of Choreo.
Demo of an end-to-end app built and deployed on Choreo.
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Anthony Dahanne
Les Buildpacks existent depuis plus de 10 ans ! D’abord, ils étaient utilisés pour détecter et construire une application avant de la déployer sur certains PaaS. Ensuite, nous avons pu créer des images Docker (OCI) avec leur dernière génération, les Cloud Native Buildpacks (CNCF en incubation). Sont-ils une bonne alternative au Dockerfile ? Que sont les buildpacks Paketo ? Quelles communautés les soutiennent et comment ?
Venez le découvrir lors de cette session ignite
How to Position Your Globus Data Portal for Success Ten Good PracticesGlobus
Science gateways allow science and engineering communities to access shared data, software, computing services, and instruments. Science gateways have gained a lot of traction in the last twenty years, as evidenced by projects such as the Science Gateways Community Institute (SGCI) and the Center of Excellence on Science Gateways (SGX3) in the US, The Australian Research Data Commons (ARDC) and its platforms in Australia, and the projects around Virtual Research Environments in Europe. A few mature frameworks have evolved with their different strengths and foci and have been taken up by a larger community such as the Globus Data Portal, Hubzero, Tapis, and Galaxy. However, even when gateways are built on successful frameworks, they continue to face the challenges of ongoing maintenance costs and how to meet the ever-expanding needs of the community they serve with enhanced features. It is not uncommon that gateways with compelling use cases are nonetheless unable to get past the prototype phase and become a full production service, or if they do, they don't survive more than a couple of years. While there is no guaranteed pathway to success, it seems likely that for any gateway there is a need for a strong community and/or solid funding streams to create and sustain its success. With over twenty years of examples to draw from, this presentation goes into detail for ten factors common to successful and enduring gateways that effectively serve as best practices for any new or developing gateway.
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisGlobus
JASMIN is the UK’s high-performance data analysis platform for environmental science, operated by STFC on behalf of the UK Natural Environment Research Council (NERC). In addition to its role in hosting the CEDA Archive (NERC’s long-term repository for climate, atmospheric science & Earth observation data in the UK), JASMIN provides a collaborative platform to a community of around 2,000 scientists in the UK and beyond, providing nearly 400 environmental science projects with working space, compute resources and tools to facilitate their work. High-performance data transfer into and out of JASMIN has always been a key feature, with many scientists bringing model outputs from supercomputers elsewhere in the UK, to analyse against observational or other model data in the CEDA Archive. A growing number of JASMIN users are now realising the benefits of using the Globus service to provide reliable and efficient data movement and other tasks in this and other contexts. Further use cases involve long-distance (intercontinental) transfers to and from JASMIN, and collecting results from a mobile atmospheric radar system, pushing data to JASMIN via a lightweight Globus deployment. We provide details of how Globus fits into our current infrastructure, our experience of the recent migration to GCSv5.4, and of our interest in developing use of the wider ecosystem of Globus services for the benefit of our user community.
Experience our free, in-depth three-part Tendenci Platform Corporate Membership Management workshop series! In Session 1 on May 14th, 2024, we began with an Introduction and Setup, mastering the configuration of your Corporate Membership Module settings to establish membership types, applications, and more. Then, on May 16th, 2024, in Session 2, we focused on binding individual members to a Corporate Membership and Corporate Reps, teaching you how to add individual members and assign Corporate Representatives to manage dues, renewals, and associated members. Finally, on May 28th, 2024, in Session 3, we covered questions and concerns, addressing any queries or issues you may have.
For more Tendenci AMS events, check out www.tendenci.com/events
top nidhi software solution freedownloadvrstrong314
This presentation emphasizes the importance of data security and legal compliance for Nidhi companies in India. It highlights how online Nidhi software solutions, like Vector Nidhi Software, offer advanced features tailored to these needs. Key aspects include encryption, access controls, and audit trails to ensure data security. The software complies with regulatory guidelines from the MCA and RBI and adheres to Nidhi Rules, 2014. With customizable, user-friendly interfaces and real-time features, these Nidhi software solutions enhance efficiency, support growth, and provide exceptional member services. The presentation concludes with contact information for further inquiries.
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamtakuyayamamoto1800
In this slide, we show the simulation example and the way to compile this solver.
In this solver, the Helmholtz equation can be solved by helmholtzFoam. Also, the Helmholtz equation with uniformly dispersed bubbles can be simulated by helmholtzBubbleFoam.
First Steps with Globus Compute Multi-User EndpointsGlobus
In this presentation we will share our experiences around getting started with the Globus Compute multi-user endpoint. Working with the Pharmacology group at the University of Auckland, we have previously written an application using Globus Compute that can offload computationally expensive steps in the researcher's workflows, which they wish to manage from their familiar Windows environments, onto the NeSI (New Zealand eScience Infrastructure) cluster. Some of the challenges we have encountered were that each researcher had to set up and manage their own single-user globus compute endpoint and that the workloads had varying resource requirements (CPUs, memory and wall time) between different runs. We hope that the multi-user endpoint will help to address these challenges and share an update on our progress here.
Globus Connect Server Deep Dive - GlobusWorld 2024Globus
We explore the Globus Connect Server (GCS) architecture and experiment with advanced configuration options and use cases. This content is targeted at system administrators who are familiar with GCS and currently operate—or are planning to operate—broader deployments at their institution.
In software engineering, the right architecture is essential for robust, scalable platforms. Wix has undergone a pivotal shift from event sourcing to a CRUD-based model for its microservices. This talk will chart the course of this pivotal journey.
Event sourcing, which records state changes as immutable events, provided robust auditing and "time travel" debugging for Wix Stores' microservices. Despite its benefits, the complexity it introduced in state management slowed development. Wix responded by adopting a simpler, unified CRUD model. This talk will explore the challenges of event sourcing and the advantages of Wix's new "CRUD on steroids" approach, which streamlines API integration and domain event management while preserving data integrity and system resilience.
Participants will gain valuable insights into Wix's strategies for ensuring atomicity in database updates and event production, as well as caching, materialization, and performance optimization techniques within a distributed system.
Join us to discover how Wix has mastered the art of balancing simplicity and extensibility, and learn how the re-adoption of the modest CRUD has turbocharged their development velocity, resilience, and scalability in a high-growth environment.
Quarkus Hidden and Forbidden ExtensionsMax Andersen
Quarkus has a vast extension ecosystem and is known for its subsonic and subatomic feature set. Some of these features are not as well known, and some extensions are less talked about, but that does not make them less interesting - quite the opposite.
Come join this talk to see some tips and tricks for using Quarkus and some of the lesser known features, extensions and development techniques.
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Globus
Large Language Models (LLMs) are currently the center of attention in the tech world, particularly for their potential to advance research. In this presentation, we'll explore a straightforward and effective method for quickly initiating inference runs on supercomputers using the vLLM tool with Globus Compute, specifically on the Polaris system at ALCF. We'll begin by briefly discussing the popularity and applications of LLMs in various fields. Following this, we will introduce the vLLM tool, and explain how it integrates with Globus Compute to efficiently manage LLM operations on Polaris. Attendees will learn the practical aspects of setting up and remotely triggering LLMs from local machines, focusing on ease of use and efficiency. This talk is ideal for researchers and practitioners looking to leverage the power of LLMs in their work, offering a clear guide to harnessing supercomputing resources for quick and effective LLM inference.
Cyaniclab : Software Development Agency Portfolio.pdfCyanic lab
CyanicLab, an offshore custom software development company based in Sweden,India, Finland, is your go-to partner for startup development and innovative web design solutions. Our expert team specializes in crafting cutting-edge software tailored to meet the unique needs of startups and established enterprises alike. From conceptualization to execution, we offer comprehensive services including web and mobile app development, UI/UX design, and ongoing software maintenance. Ready to elevate your business? Contact CyanicLab today and let us propel your vision to success with our top-notch IT solutions.
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxrickgrimesss22
Discover the essential features to incorporate in your Winzo clone app to boost business growth, enhance user engagement, and drive revenue. Learn how to create a compelling gaming experience that stands out in the competitive market.
4. Delegates
• Delegate
– A delegate is an object that points to a function
– is basically a function pointer, C++!
– "Why do I need a reference to a method?"
• The answer boils down to giving you maximum flexibility to implement any functionality you want at
runtime.
– You can use delegate to pass a function as a parameter
5. Delegate Example
public class MagicNumber
{
public int Number { get; set; }
}
public void Increment(MagicNumber magicNumber)
{
magicNumber.Number++;
}
public void Decrement(MagicNumber magicNumber)
{
magicNumber.Number--;
}
public delegate void MagicNumberModifier (MagicNumber magicNumber);
Delegate Declaration
6. Delegate Example
• Now let’s make a list of MagicNumbers
• And a member like this:
List<MagicNumber> magicNumbers = new List<MagicNumber>();
magicNumbers.Add(new MagicNumber() { Number = 4});
magicNumbers.Add(new MagicNumber() { Number = 6});
magicNumbers.Add(new MagicNumber() { Number = 9});
magicNumbers.Add(new MagicNumber() { Number = 13});
magicNumbers.Add(new MagicNumber() { Number = 20});
public static void ApplyModifierToAll(MagicNumberModifier modifier, List<MagicNumber>
magicNumbers)
{
foreach(MagicNumber number in magicNumbers)
{
modifier(number);
}
}
Delegate!
public delegate void MagicNumberModifier (MagicNumber magicNumber);
7. Delegate Example
• Lastly, just call the delegate and let the magic happens
public static void Main(string[] args)
{
List<MagicNumber> magicNumbers = new List<MagicNumber>();
magicNumbers.Add(new MagicNumber() { Number = 4, IsMagic = true });
magicNumbers.Add(new MagicNumber() { Number = 6, IsMagic = false });
magicNumbers.Add(new MagicNumber() { Number = 9, IsMagic = true });
magicNumbers.Add(new MagicNumber() { Number = 13, IsMagic = false });
magicNumbers.Add(new MagicNumber() { Number = 20, IsMagic = true });
ApplyModifierToAll(Increment, magicNumbers);
ApplyModifierToAll(Magicify, magicNumbers);
}
8. MultiCasting-Delegates
• Note!
– If you chain delegates that return values, you may run into some problems. The way C#
handles that situation is by returning the value of only the last function inside the delegate. All
other return values are discarded. So don’t return things that are absolutely vital to your
program if you know the function is going inside a chained delegate.
12. public class Point
{
private double x;
private double y;
public double X
{
get
{
return x;
}
set
{
x = value;
OnPointChanged();
}
}
public double Y
{
get
{
return y;
}
set
{
y = value;
OnPointChanged();
}
}
public event EventHandler PointChanged;
public void OnPointChanged()
{
if(PointChanged != null)
{
PointChanged(this, EventArgs.Empty);
}
}
}
13. public class Point
{
private double x;
private double y;
public double X
{
get
{
return x;
}
set
{
x = value;
OnPointChanged();
}
}
public double Y
{
get
{
return y;
}
set
{
y = value;
OnPointChanged();
}
}
public event EventHandler PointChanged;
public void OnPointChanged()
{
if(PointChanged != null)
{
PointChanged(this, EventArgs.Empty);
}
}
}
14. public class Point
{
private double x;
private double y;
public double X
{
get
{
return x;
}
set
{
x = value;
OnPointChanged();
}
}
public double Y
{
get
{
return y;
}
set
{
y = value;
OnPointChanged();
}
}
public event EventHandler PointChanged;
public void OnPointChanged()
{
if(PointChanged != null)
{
PointChanged(this, EventArgs.Empty);
}
}
}
15. public class Point
{
private double x;
private double y;
public double X
{
get
{
return x;
}
set
{
x = value;
OnPointChanged();
}
}
public double Y
{
get
{
return y;
}
set
{
y = value;
OnPointChanged();
}
}
public event EventHandler PointChanged;
public void OnPointChanged()
{
if(PointChanged != null)
{
PointChanged(this, EventArgs.Empty);
}
}
}
The event handler
Raising the event
17. public class Point
{
private double x;
private double y;
public double X
{
get
{
return x;
}
set
{
x = value;
OnPointChanged();
}
}
public double Y
{
get
{
return y;
}
set
{
y = value;
OnPointChanged();
}
}
public event EventHandler PointChanged;
public void OnPointChanged()
{
if(PointChanged != null)
{
PointChanged(this, EventArgs.Empty);
}
}
}
class Program
{
public static void Main()
{
new Program().Test();
}
private void Test()
{
Point point = new Point();
// Here's the real important line:
point.PointChanged += HandlePointChanged;
// Now if we change the point, the PointChanged event will get raised,
// and HandlePointChanged will get called.
point.X = 3;
}
public void HandlePointChanged(object sender, EventArgs eventArgs)
{
// Do something intelligent when the point changes. Perhaps redraw the GUI,
// or update another data structure, or anything else you can think of.
}
}
19. public class Point
{
private double x;
private double y;
public double X
{
get
{
return x;
}
set
{
x = value;
OnPointChanged();
}
}
public double Y
{
get
{
return y;
}
set
{
y = value;
OnPointChanged();
}
}
public event EventHandler PointChanged;
public void OnPointChanged()
{
if(PointChanged != null)
{
PointChanged(this, EventArgs.Empty);
}
}
}
class Program
{
public static void Main()
{
new Program().Test();
}
private void Test()
{
Point point = new Point();
// Here's the real important line:
point.PointChanged += HandlePointChanged;
// Now if we change the point, the PointChanged event will get raised,
// and HandlePointChanged will get called.
point.X = 3;
}
public void HandlePointChanged(object sender, EventArgs eventArgs)
{
// Do something intelligent when the point changes. Perhaps redraw the GUI,
// or update another data structure, or anything else you can think of.
}
}
When a point is Set the
method OnPointChanged
will be called
20. public class Point
{
private double x;
private double y;
public double X
{
get
{
return x;
}
set
{
x = value;
OnPointChanged();
}
}
public double Y
{
get
{
return y;
}
set
{
y = value;
OnPointChanged();
}
}
public event EventHandler PointChanged;
public void OnPointChanged()
{
if(PointChanged != null)
{
PointChanged(this, EventArgs.Empty);
}
}
}
class Program
{
public static void Main()
{
new Program().Test();
}
private void Test()
{
Point point = new Point();
// Here's the real important line:
point.PointChanged += HandlePointChanged;
// Now if we change the point, the PointChanged event will get raised,
// and HandlePointChanged will get called.
point.X = 3;
}
public void HandlePointChanged(object sender, EventArgs eventArgs)
{
// Do something intelligent when the point changes. Perhaps redraw the GUI,
// or update another data structure, or anything else you can think of.
}
}
Which will consequently
raise the event by calling it
(checking if the delegate is
null for the first time)
21. public class Point
{
private double x;
private double y;
public double X
{
get
{
return x;
}
set
{
x = value;
OnPointChanged();
}
}
public double Y
{
get
{
return y;
}
set
{
y = value;
OnPointChanged();
}
}
public event EventHandler PointChanged;
public void OnPointChanged()
{
if(PointChanged != null)
{
PointChanged(this, EventArgs.Empty);
}
}
}
class Program
{
public static void Main()
{
new Program().Test();
}
private void Test()
{
Point point = new Point();
// Here's the real important line:
point.PointChanged += HandlePointChanged;
// Now if we change the point, the PointChanged event will get raised,
// and HandlePointChanged will get called.
point.X = 3;
}
public void HandlePointChanged(object sender, EventArgs eventArgs)
{
// Do something intelligent when the point changes. Perhaps redraw the GUI,
// or update another data structure, or anything else you can think of.
}
}
And consequently, calling
the delegate that points to
the programmer function
22. public class Point
{
private double x;
private double y;
public double X
{
get
{
return x;
}
set
{
x = value;
OnPointChanged();
}
}
public double Y
{
get
{
return y;
}
set
{
y = value;
OnPointChanged();
}
}
public event EventHandler PointChanged;
public void OnPointChanged()
{
if(PointChanged != null)
{
PointChanged(this, EventArgs.Empty);
}
}
}
class Program
{
public static void Main()
{
new Program().Test();
}
private void Test()
{
Point point = new Point();
// Here's the real important line:
point.PointChanged += HandlePointChanged;
// Now if we change the point, the PointChanged event will get raised,
// and HandlePointChanged will get called.
point.X = 3;
}
public void HandlePointChanged(object sender, EventArgs eventArgs)
{
// Do something intelligent when the point changes. Perhaps redraw the GUI,
// or update another data structure, or anything else you can think of.
}
}
And consequently, calling
the delegate that points to
the programmer function
23. Attaching/Detaching Multiple Events
• The event can easily be removed/changed/added at runtime by -= or +=
• An event can also add multiple function pointers (delegates at the same time),
pointing at all of them at the same time and calling all of them when the event is
raised!
point.PointChanged -= HandlePointChanged;
point.PointChanged += HandlePointChanged;
point.PointChanged += HandlePotatoPositionChange;
25. Anonymous Methods
• An anonymous method is a method without a name
– which is why it is called anonymous.
• You don't declare anonymous methods like regular methods.
– Instead they get hooked up directly to events.
26. Anonymous Methods
using System.Windows.Forms;
public partial class Form1 : Form
{
public Form1()
{
Button buttonHello = new Button();
buttonHello.Text = "Hello";
buttonHello.Click +=
delegate
{
MessageBox.Show("Hello");
};
Controls.Add(buttonHello);
}
}
27. Anonymous Methods
using System.Windows.Forms;
public partial class Form1 : Form
{
public Form1()
{
Button buttonHello = new Button();
buttonHello.Text = "Hello";
buttonHello.Click +=
delegate
{
MessageBox.Show("Hello");
};
Controls.Add(buttonHello);
}
}
28. Anonymous Methods
public partial class Form1 : Form
{
public Form1()
{
Button buttonHello = new Button();
buttonHello.Text = "Hello";
buttonHello.Click +=
delegate
{
MessageBox.Show("Hello");
};
Button btnGoodBye = new Button();
btnGoodBye.Text = "Goodbye";
btnGoodBye.Left = buttonHello.Width + 5;
btnGoodBye.Click +=
delegate(object sender, EventArgs e)
{
string message = (sender as Button).Text;
MessageBox.Show(message);
};
Controls.Add(buttonHello);
Controls.Add(btnGoodBye);
}
}
29. Anonymous Methods
public partial class Form1 : Form
{
public Form1()
{
Button buttonHello = new Button();
buttonHello.Text = "Hello";
buttonHello.Click +=
delegate
{
MessageBox.Show("Hello");
};
Button btnGoodBye = new Button();
btnGoodBye.Text = "Goodbye";
btnGoodBye.Left = buttonHello.Width + 5;
btnGoodBye.Click +=
delegate(object sender, EventArgs e)
{
string message = (sender as Button).Text;
MessageBox.Show(message);
};
Controls.Add(buttonHello);
Controls.Add(btnGoodBye);
}
}
30. Anonymous Methods
public partial class Form1 : Form
{
public Form1()
{
Button buttonHello = new Button();
buttonHello.Text = "Hello";
buttonHello.Click +=
delegate
{
MessageBox.Show("Hello");
};
Button btnGoodBye = new Button();
btnGoodBye.Text = "Goodbye";
btnGoodBye.Left = buttonHello.Width + 5;
btnGoodBye.Click +=
delegate(object sender, EventArgs e)
{
string message = (sender as Button).Text;
MessageBox.Show(message);
};
Controls.Add(buttonHello);
Controls.Add(btnGoodBye);
}
}
31. Anonymous Methods
public partial class Form1 : Form
{
public Form1()
{
Button buttonHello = new Button();
buttonHello.Text = "Hello";
buttonHello.Click +=
delegate
{
MessageBox.Show("Hello");
};
Button btnGoodBye = new Button();
btnGoodBye.Text = "Goodbye";
btnGoodBye.Left = buttonHello.Width + 5;
btnGoodBye.Click +=
delegate(object sender, EventArgs e)
{
string message = (sender as Button).Text;
MessageBox.Show(message);
};
Controls.Add(buttonHello);
Controls.Add(btnGoodBye);
}
}
32. Anonymous Methods
public partial class Form1 : Form
{
public Form1()
{
Button buttonHello = new Button();
buttonHello.Text = "Hello";
buttonHello.Click +=
delegate
{
MessageBox.Show("Hello");
};
Button btnGoodBye = new Button();
btnGoodBye.Text = "Goodbye";
btnGoodBye.Left = buttonHello.Width + 5;
btnGoodBye.Click +=
delegate(object sender, EventArgs e)
{
string message = (sender as Button).Text;
MessageBox.Show(message);
};
Controls.Add(buttonHello);
Controls.Add(btnGoodBye);
}
}
34. Extension Methods
Extension methods are a way to create a method that feels like it is part of a specific class
(like, the string class) when you don't actually have access to that class to modify, and add the
method.
36. Extension Methods
It’s a way to add functionalities to classes you don’t own
that’s why they are called Extension Methods
37. Extension Methods
• Extension methods must be added in static classes (where methods in that static
class should also be static)
• Now, Let’s extend the String class with a ToRandomCase method that
randomize the letter cases in a given string.
38. Extension Methods
public static class StringExtensions
{
private static Random random = new Random();
public static string ToRandomCase(this string text)
{
string result = "";
for (int index = 0; index < text.Length; index++)
{
if (random.Next(2) == 0)
{
result += text.Substring(index, 1).ToUpper();
}
else
{
result += text.Substring(index, 1).ToLower();
}
}
return result;
}
}
Static class
39. Extension Methods
public static class StringExtensions
{
private static Random random = new Random();
public static string ToRandomCase(this string text)
{
string result = "";
for (int index = 0; index < text.Length; index++)
{
if (random.Next(2) == 0)
{
result += text.Substring(index, 1).ToUpper();
}
else
{
result += text.Substring(index, 1).ToLower();
}
}
return result;
}
}
Static data member
40. Extension Methods
public static class StringExtensions
{
private static Random random = new Random();
public static string ToRandomCase(this string text)
{
string result = "";
for (int index = 0; index < text.Length; index++)
{
if (random.Next(2) == 0)
{
result += text.Substring(index, 1).ToUpper();
}
else
{
result += text.Substring(index, 1).ToLower();
}
}
return result;
}
}
Static method
41. Extension Methods
public static class StringExtensions
{
private static Random random = new Random();
public static string ToRandomCase(this string text)
{
string result = "";
for (int index = 0; index < text.Length; index++)
{
if (random.Next(2) == 0)
{
result += text.Substring(index, 1).ToUpper();
}
else
{
result += text.Substring(index, 1).ToLower();
}
}
return result;
}
}
The extended class (string)
with the this keyword
42. Extension Methods
public static class StringExtensions
{
private static Random random = new Random();
public static string ToRandomCase(this string text)
{
string result = "";
for (int index = 0; index < text.Length; index++)
{
if (random.Next(2) == 0)
{
result += text.Substring(index, 1).ToUpper();
}
else
{
result += text.Substring(index, 1).ToLower();
}
}
return result;
}
}
A simple randomization
algorithm
43. Extension Methods
• Now just call the method!
public static void Main()
{
string message = "Do you wish me a good morning, or mean that it is a good morning whether I
want it or not; or that you feel good this morning; or that it is a morning to be good on?";
Console.WriteLine(message.ToRandomCase());
}
Do You WisH mE A gOOD MOrniNG, Or mEan that it iS a GOOD moRnIng wHether i Want It or noT; Or that yOu
feeL goOD THiS morning; OR tHaT it iS A MOrNINg to be GoOd On?
Press any key to continue . . .