This document summarizes new generic types and features in C# 4, including Lazy<T> for deferred initialization, tuples for ad-hoc data structures, and generic variance. Generic variance allows covariant and contravariant conversions between generic types to promote substitutability. It was enabled for interfaces and delegates in C# 4 through explicit variance declarations like "out T" and "in T". This improves type safety over arrays, which allow unsafe covariance in C#.
Decision making:
In CSharp, various types of decision making statements are available such as if..else, if..else..if, switch etc. Each statement is used to evaluate the specific test. If tests are determined to be true, specific statement will be execued for example : if(a > b) statement1 else statement2. Sometimes when develpoing program that requires to take the decision to execute specific part of program, decision making statement helps to do so.
Switch Case
In CSharp switch acts like a multiple if / else if / else chain. Checks a value against a list of cases, and executes the first case that is true. If no matching case found, it executes the default case. The break(optional) statements with case indicate to the interpreter to end the particular case.
The presentation starts with some basic theory on types. Later, different classifications for type systems are described, with the static/dynamic and strong/weak dimensions the ones we spend more time on.
The third topic addressed is how the mix of polimorsfism with covariance and descendant hiding affects the type system, and what new problems arise and have to be addressed by the type system.
We finished the presentation with a discussion about pros and cons of the PHP type system.
Decision making:
In CSharp, various types of decision making statements are available such as if..else, if..else..if, switch etc. Each statement is used to evaluate the specific test. If tests are determined to be true, specific statement will be execued for example : if(a > b) statement1 else statement2. Sometimes when develpoing program that requires to take the decision to execute specific part of program, decision making statement helps to do so.
Switch Case
In CSharp switch acts like a multiple if / else if / else chain. Checks a value against a list of cases, and executes the first case that is true. If no matching case found, it executes the default case. The break(optional) statements with case indicate to the interpreter to end the particular case.
The presentation starts with some basic theory on types. Later, different classifications for type systems are described, with the static/dynamic and strong/weak dimensions the ones we spend more time on.
The third topic addressed is how the mix of polimorsfism with covariance and descendant hiding affects the type system, and what new problems arise and have to be addressed by the type system.
We finished the presentation with a discussion about pros and cons of the PHP type system.
Clean code is a reader-focused development style that produces software that's easy to write, read and maintain. In this slide deck clean code has been presented briefly.
Slides: http://pa4373.github.io/jstutorials_corepart/
GitHub Repo: https://github.com/pa4373/jstutorials_corepart
This is the first part of JavaScript programming tutorials. This tutorial introduces the brief history of JavaScript, the relationship of the specification and a variety of implementations, and then the basic syntax and the concepts are introduced, that can be generally applied to programming interactions with different runtimes.
Parse::Eyapp is a collection of modules
that extends Francois Desarmenien Parse::Yapp 1.05.
Eyapp extends yacc/yapp syntax with
functionalities like named attributes,
EBNF-like expressions, modifiable default action,
automatic abstract syntax tree building,
dynamic conflict resolution,
translation schemes, tree regular expressions,
tree transformations, scope analysis support,
and directed acyclic graphs among others.
This article teaches you the basics of
Compiler Construction using Parse::Eyap to
build a translator from infix expressions to Parrot
Intermediate Representation.
Show features introduced in C# 6.0 followed by a first look Into C# 7.0
A presentation at DDD Melbourne 2016 by @softveda. http://www.dddmelbourne.com/
Pointers and C Programming,
It is not Included: Function Pointer , Structure Pointer and Pointer of Pointer, It is On Demand Tutorial.
vikram snehi ,snehi ,pointers ,integer pointer ,c programming ,pointers in c program ,nowstart.in
vikram snehi ,snehi ,pointers ,integer pointer ,c programming ,pointers in c program ,nowstart.in
Overview of Groovy language features and lead to Functional Programming in Groovy. As this is a code along session backed by this presentation, code examples are not include here as I code them live.
Clean code is a reader-focused development style that produces software that's easy to write, read and maintain. In this slide deck clean code has been presented briefly.
Slides: http://pa4373.github.io/jstutorials_corepart/
GitHub Repo: https://github.com/pa4373/jstutorials_corepart
This is the first part of JavaScript programming tutorials. This tutorial introduces the brief history of JavaScript, the relationship of the specification and a variety of implementations, and then the basic syntax and the concepts are introduced, that can be generally applied to programming interactions with different runtimes.
Parse::Eyapp is a collection of modules
that extends Francois Desarmenien Parse::Yapp 1.05.
Eyapp extends yacc/yapp syntax with
functionalities like named attributes,
EBNF-like expressions, modifiable default action,
automatic abstract syntax tree building,
dynamic conflict resolution,
translation schemes, tree regular expressions,
tree transformations, scope analysis support,
and directed acyclic graphs among others.
This article teaches you the basics of
Compiler Construction using Parse::Eyap to
build a translator from infix expressions to Parrot
Intermediate Representation.
Show features introduced in C# 6.0 followed by a first look Into C# 7.0
A presentation at DDD Melbourne 2016 by @softveda. http://www.dddmelbourne.com/
Pointers and C Programming,
It is not Included: Function Pointer , Structure Pointer and Pointer of Pointer, It is On Demand Tutorial.
vikram snehi ,snehi ,pointers ,integer pointer ,c programming ,pointers in c program ,nowstart.in
vikram snehi ,snehi ,pointers ,integer pointer ,c programming ,pointers in c program ,nowstart.in
Overview of Groovy language features and lead to Functional Programming in Groovy. As this is a code along session backed by this presentation, code examples are not include here as I code them live.
The F# community has been steadily working on extensions to the F# core libraries. These extensions provide helpful features that are "missing," add common parts found in other functional languages, and help with compatibility in other .NET languages.
(4) cpp automatic arrays_pointers_c-stringsNico Ludwig
Check out these exercises: http://de.slideshare.net/nicolayludwig/4-cpp-automatic-arrayspointerscstringsexercises-38510502
- Pointers: Call by Value versus Call by Reference
- Automatic Arrays
- Arrays and Pointer Decay
- Pointers to Pointers
- C-strings as Arrays and their Memory Representation
- Basic C-string Functions
How can we implement concepts of Lambda Calculus and Category Theory in C# and F#:
- Lambda Calculus: The importance of expressions to build a robust and reasonable program flow
- Category Theory: How to apply functional concepts like functors, applicatives or monads to deal wit
Check out these exercises: http://de.slideshare.net/nicolayludwig/2-cpp-imperative-programmingexercises
- Imperative Programming
- Style and Conventions
- Constants
- Fundamental Types
- Console Basics
- Operators, Precedence, Associativity and Evaluation Order
- Control Structures and Blocks
Check out these exercises: http://de.slideshare.net/nicolayludwig/3-cpp-procedural-programmingexercises
- Procedural Programming
- Predefined and User defined Functions
- Declaration and Definition of Functions
- Procedural and recursive Function Calling
- Namespaces and separated Function Definitions
- A Glimpse of Separated Compilation and Translation Units
Von Gleichungen zu Funktionen
Überblick über ganzrationale Funktionen
Koordinatensysteme für Graphen ganzrationaler Funktionen mit Excels Liniendiagrammen erstellen
Einfache Analyse ganzrationaler Funktionen anhand deren Graphen
Von linearen zu quadratischen Gleichungssystemen
Verschiedene Möglichkeiten quadratische Gleichungssysteme grafisch zu lösen
Koordinatensysteme für quadratische Graphen mit Excels Liniendiagrammen erstellen und Gleichungen damit grafisch lösen
Grafische Interpretation der Lösungen von Normalparabel-Gerade Kombinationen
Diagramme
Einführung linearer Gleichungssysteme mit zwei Unbekannten
Rechnerische und grafische Lösung linearer Gleichungssysteme
Wertetabellen mit Excel erstellen
Koordinatensysteme und lineare Graphen mit Excels Liniendiagrammen erstellen und Gleichungen damit grafisch lösen
Mit großen Tabellen arbeiten
Sortieren und Filtern
Objekte einfügen
Formeln und rechnen mit Excel, insbesondere Zahlen und Textbearbeitung
Relative und absolute Zellbezüge
Funktionen: SUMME(), ANZAHL(), MIN(), MAX(), MITTELWERT(), JETZT(), HEUTE(), ZUFALLSZAHL(), PI() und SUMMEWENN()
Mathematische Probleme in Tabellenform
Geschichtliche Entwicklung
Grundlegende Konzepte und Begriffe in Excel
Selektion, Dateneingabe und Datentypen
Zellformatierung und Inhaltsformatierung
- Vector- and Raster-based Graphics
-- Idea behind Vector- and Raster-based Graphics
-- Crispness
-- Overview of Raster-based Drawing APIs
- Platform independent Graphics and GUIs in the Web Browser
-- Bare HTML Pages
-- Plugins and Problems
-- From rich Content to HTML 5
- Drawing with HTML 5 Canvas
-- Continuous, Event driven and free Drawing
-- Basic Drawing "How does Drawing work with JavaScript?"
-- Interaction with Controls
- Vector- and Raster-based Graphics
-- Idea behind Vector- and Raster-based Graphics
-- Crispness
-- Overview of Raster-based Drawing APIs
- Platform independent Graphics and GUIs in the Web Browser
-- Bare HTML Pages
-- Plugins and Problems
-- From rich Content to HTML 5
- Drawing with HTML 5 Canvas
-- Continuous, Event driven and free Drawing
-- Basic Drawing "How does Drawing work with JavaScript?"
-- Interaction with Controls
- Wires and Bulbs
- Batch Processing
- Terminal and Mainframe
- From the Command-Line to Killer Applications
- Vector Displays and Raster Displays
- Color Displays
- The Mouse and the Takeoff of Interactivity
- The Desktop Metaphor
- Wires and Bulbs
- Batch Processing
- Terminal and Mainframe
- From the Command-Line to Killer Applications
- Vector Displays and Raster Displays
- Color Displays
- The Mouse and the Takeoff of Interactivity
- The Desktop Metaphor
(7) c sharp introduction_advanvced_features_part_iiNico Ludwig
This presentation comes with many additional notes (pdf): http://de.slideshare.net/nicolayludwig/7-c-sharp-introductionadvanvcedfeaturespartii-38640489
Check out these exercises: http://de.slideshare.net/nicolayludwig/6-7-c-sharp-introductionadvancedfeaturespartipartiiexercises
- Object-based and generic Collections
- Delegates and Events
- Custom Attributes
- Reflection
GraphRAG is All You need? LLM & Knowledge GraphGuy Korland
Guy Korland, CEO and Co-founder of FalkorDB, will review two articles on the integration of language models with knowledge graphs.
1. Unifying Large Language Models and Knowledge Graphs: A Roadmap.
https://arxiv.org/abs/2306.08302
2. Microsoft Research's GraphRAG paper and a review paper on various uses of knowledge graphs:
https://www.microsoft.com/en-us/research/blog/graphrag-unlocking-llm-discovery-on-narrative-private-data/
UiPath Test Automation using UiPath Test Suite series, part 4DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 4. In this session, we will cover Test Manager overview along with SAP heatmap.
The UiPath Test Manager overview with SAP heatmap webinar offers a concise yet comprehensive exploration of the role of a Test Manager within SAP environments, coupled with the utilization of heatmaps for effective testing strategies.
Participants will gain insights into the responsibilities, challenges, and best practices associated with test management in SAP projects. Additionally, the webinar delves into the significance of heatmaps as a visual aid for identifying testing priorities, areas of risk, and resource allocation within SAP landscapes. Through this session, attendees can expect to enhance their understanding of test management principles while learning practical approaches to optimize testing processes in SAP environments using heatmap visualization techniques
What will you get from this session?
1. Insights into SAP testing best practices
2. Heatmap utilization for testing
3. Optimization of testing processes
4. Demo
Topics covered:
Execution from the test manager
Orchestrator execution result
Defect reporting
SAP heatmap example with demo
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Jeffrey Haguewood
Sidekick Solutions uses Bonterra Impact Management (fka Social Solutions Apricot) and automation solutions to integrate data for business workflows.
We believe integration and automation are essential to user experience and the promise of efficient work through technology. Automation is the critical ingredient to realizing that full vision. We develop integration products and services for Bonterra Case Management software to support the deployment of automations for a variety of use cases.
This video focuses on the notifications, alerts, and approval requests using Slack for Bonterra Impact Management. The solutions covered in this webinar can also be deployed for Microsoft Teams.
Interested in deploying notification automations for Bonterra Impact Management? Contact us at sales@sidekicksolutionsllc.com to discuss next steps.
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Ramesh Iyer
In today's fast-changing business world, Companies that adapt and embrace new ideas often need help to keep up with the competition. However, fostering a culture of innovation takes much work. It takes vision, leadership and willingness to take risks in the right proportion. Sachin Dev Duggal, co-founder of Builder.ai, has perfected the art of this balance, creating a company culture where creativity and growth are nurtured at each stage.
Securing your Kubernetes cluster_ a step-by-step guide to success !KatiaHIMEUR1
Today, after several years of existence, an extremely active community and an ultra-dynamic ecosystem, Kubernetes has established itself as the de facto standard in container orchestration. Thanks to a wide range of managed services, it has never been so easy to set up a ready-to-use Kubernetes cluster.
However, this ease of use means that the subject of security in Kubernetes is often left for later, or even neglected. This exposes companies to significant risks.
In this talk, I'll show you step-by-step how to secure your Kubernetes cluster for greater peace of mind and reliability.
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties – USA
Expansion of bot farms – how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks – Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
Essentials of Automations: Optimizing FME Workflows with ParametersSafe Software
Are you looking to streamline your workflows and boost your projects’ efficiency? Do you find yourself searching for ways to add flexibility and control over your FME workflows? If so, you’re in the right place.
Join us for an insightful dive into the world of FME parameters, a critical element in optimizing workflow efficiency. This webinar marks the beginning of our three-part “Essentials of Automation” series. This first webinar is designed to equip you with the knowledge and skills to utilize parameters effectively: enhancing the flexibility, maintainability, and user control of your FME projects.
Here’s what you’ll gain:
- Essentials of FME Parameters: Understand the pivotal role of parameters, including Reader/Writer, Transformer, User, and FME Flow categories. Discover how they are the key to unlocking automation and optimization within your workflows.
- Practical Applications in FME Form: Delve into key user parameter types including choice, connections, and file URLs. Allow users to control how a workflow runs, making your workflows more reusable. Learn to import values and deliver the best user experience for your workflows while enhancing accuracy.
- Optimization Strategies in FME Flow: Explore the creation and strategic deployment of parameters in FME Flow, including the use of deployment and geometry parameters, to maximize workflow efficiency.
- Pro Tips for Success: Gain insights on parameterizing connections and leveraging new features like Conditional Visibility for clarity and simplicity.
We’ll wrap up with a glimpse into future webinars, followed by a Q&A session to address your specific questions surrounding this topic.
Don’t miss this opportunity to elevate your FME expertise and drive your projects to new heights of efficiency.
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualityInflectra
In this insightful webinar, Inflectra explores how artificial intelligence (AI) is transforming software development and testing. Discover how AI-powered tools are revolutionizing every stage of the software development lifecycle (SDLC), from design and prototyping to testing, deployment, and monitoring.
Learn about:
• The Future of Testing: How AI is shifting testing towards verification, analysis, and higher-level skills, while reducing repetitive tasks.
• Test Automation: How AI-powered test case generation, optimization, and self-healing tests are making testing more efficient and effective.
• Visual Testing: Explore the emerging capabilities of AI in visual testing and how it's set to revolutionize UI verification.
• Inflectra's AI Solutions: See demonstrations of Inflectra's cutting-edge AI tools like the ChatGPT plugin and Azure Open AI platform, designed to streamline your testing process.
Whether you're a developer, tester, or QA professional, this webinar will give you valuable insights into how AI is shaping the future of software delivery.
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...UiPathCommunity
💥 Speed, accuracy, and scaling – discover the superpowers of GenAI in action with UiPath Document Understanding and Communications Mining™:
See how to accelerate model training and optimize model performance with active learning
Learn about the latest enhancements to out-of-the-box document processing – with little to no training required
Get an exclusive demo of the new family of UiPath LLMs – GenAI models specialized for processing different types of documents and messages
This is a hands-on session specifically designed for automation developers and AI enthusiasts seeking to enhance their knowledge in leveraging the latest intelligent document processing capabilities offered by UiPath.
Speakers:
👨🏫 Andras Palfi, Senior Product Manager, UiPath
👩🏫 Lenka Dulovicova, Product Program Manager, UiPath
Generating a custom Ruby SDK for your web service or Rails API using Smithyg2nightmarescribd
Have you ever wanted a Ruby client API to communicate with your web service? Smithy is a protocol-agnostic language for defining services and SDKs. Smithy Ruby is an implementation of Smithy that generates a Ruby SDK using a Smithy model. In this talk, we will explore Smithy and Smithy Ruby to learn how to generate custom feature-rich SDKs that can communicate with any web service, such as a Rails JSON API.
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
New c sharp4_features_part_ii
1. 1
New C#4 Features – Part II
Nico Ludwig (@ersatzteilchen)
2. 2
TOC
● New C#4 Features – Part II
– New generic Types of the BCL in Detail: Lazy<T> and Tuple<T, ...>
– Generic Variance
● Sources:
– Jon Skeet, CSharp in Depth
– Chamond Liu, Smalltalk, Objects, Design
3. 3
New generic BCL Types
<NewGenericBCLTypes>
TShows the type Lazy<T>, Tuples and structural comparison
with Tuples and arrays.
4. 4
Lazy<T>
● Lazy<T> provides simple support for deferred initialization.
– Idiomatic usage as (encapsulated) field of a type.
● Lazy initialization w/ dctors as well as w/ initializer functions is supported.
● Threadsafe initialization is supported.
5. 5
Tuples – Part I
● Tuples are known from functional programming as ad hoc data structure.
– A Tuple is: Basically a list of values (called components) of possibly different static types.
– They have been introduced to use F# APIs that make use of Tuples.
– .Net Tuples are ordinary generic types, but can have any number of components.
● There are generic overloads for up to seven components.
● This limit can be overcome by cascading Tuples.
● Tuples vs. anonymous types:
– Only Tuples (as static type) can be returned from methods and passed to methods.
– Only anonymous types have semantic quality, Tuples are rather data containers.
– Both override Equals() and GetHashCode() in order to express value semantics.
– Both are immutable in C#.
● Slightly like Lisp's concept of cons-cells.
● As the Tuple-types are not sealed you could
derive your own implementation containing
extra behavior. - But that's questionable as you
can't hide possibly unwanted information (like
the ItemX-properties accessing the
components).
● Tuples can't be XML serialized (this esp.
includes that they don't have a dctor).
6. 6
Tuples – Part II
● Pro:
– Allow creating more composable APIs.
● As alternative to passing back results with out/ref.
● Also very handy as return type of anonymous functions (e.g. in TPL code).
– Support structural comparison.
● New in .Net 4: arrays also implement IStructuralEquatable and IStructuralComparable explicitly.
– Allow exploiting F# APIs that deal with Tuples.
● Contra:
– As they have fixed property names, they have very limited semantics.
● Limit their usage to return types and parameter types.
● Understand and use them as data containers.
– Can't be used in web service interfaces, as Tuples can not be accordingly serialized.
● Using of Tuples can be better than anonymous
types, if you need to return the result of an
anonymous function from an enclosing _named_
function!
● Tuples are fine to create fluent APIs, as they allow
to get rid of ref and out parameters.
7. 7
Consistency of Type Hierarchies: Covariance
● What does "consistency" mean?
– The idea is to design type-safe type hierarchies with highly substitutable types.
– The key to get this consistency is subtype or subclass based conformance.
– (We'll discuss the Liskov Substitution Principle (LSP) on a high level here.)
● Example: Let's assume Birds that lay Eggs "consistently" with static typing:
– If the type Bird lays an Egg, wouldn't a Bird's subtype lay a subtype of Egg?
– E.g. the type Duck lays a DuckEgg; then the consistency is given like so:
DuckEgg
– Why is this consistent? Because in such an expression (no C#!):
+ Lay : Egg
Egg anEgg = aBird.Lay()
Bird
the reference aBird could be legally substituted by a Bird or by a Duck instance.
– We say the return type is covariant to the type, in which Lay() is defined.
– A subtype's override may return a more specialized type. => "They deliver more."
Duck
+ Lay : DuckEgg
Egg
● The term sub typing is used here a little sloppy.
Virtually the terms sub typing and sub classing
have different meanings when discussing
substitutability, but the difference is not relevant
here.
● The LSP was introduced by Prof. (MIT) Barbara
Liskov in 1987.
● Covariance is esp. handy on abstract factories.
● Exception specifications in C++ and Java are also
covariant (as they are similar to return types).
● Covariance/contravariance are terms taken from
the mathematical "category theory" that deals with
the substitution principle.
8. 8
Consistency of Type Hierarchies: Contravariance
● Let's assume Pianos that Pianists can play "consistently" with static typing:
– If a Pianist plays Piano, would she be able to play aGrandPiano?
– Wouldn't rather a Virtuoso play a GrandPiano? (Be warned; there is a twist!)
Virtuoso
– This is inconsistent! Because in such an expression (no C#):
+ Play(player : Pianist)
aPiano.Play(aPianist)
Piano
– aPiano couldn't be legally substituted by a Piano or by a GrandPiano instance! A GrandPiano can only be played by a Virtuoso,
Pianists are too general!
– GrandPianos must be playable by more general types, then the play is consistent:
– We say the parameter type is contravariant to the type, in which Play() is defined.
– A subtype's override may accept a more generalized type. => "They require less."
GrandPiano
+ Play(player : Virtuoso)
Pianist
Pianist
Piano
+ Play(player : Pianist)
GrandPiano
+ Play(player : Person)
Person
● The described conformance (covariant return
types/contravariant parameter types) is the
theoretical ideal (supported by the languages
Emerald and POOL-1). Some oop languages (e.g.
Eiffel) decided to apply another type of
consistency, esp. also covariant parameter types,
because it better describes the reality than the
theoretical ideal.
● In statically typed languages the desired
consistency must often be achieved by application
of design patterns like "double dispatching" and
"visitor". Other languages provide so-called
"multiple dispatch" (e.g. CLOS) or get the desired
effect by using dynamic typing.
9. 9
Problems with covariant Arrays in C#
<IntrinsicCSharpCovarianceWArrays>
Shows the problem with covariance of arrays in C#.
10. 10
Put the Consistency Theory into Practice with C#4
● Variance expresses the consistency of type-safe type substitution.
● C# does already provide covariance on arrays.
– Yes, it's not type-safe, but can we do anything more to reach better consistency?
● Yes, via generic variance available in C#4!
– (But C#'s consistency is still based on invariant return and parameter types!)
● So, you can enable variances on generic delegate and interface types.
– This feature was present since .Net 2, it was enabled for C# in C#4.
– The idea is to define the variance of return and parameter types individually.
– Different variances can be mixed in a specific delegate or interface.
– With variance, the compiler will treat in and out - types differently, so that variant generic types act as if they were related.
● Covariance on arrays works only w/ reference
conversions: inheritance and interface (of
implicitly or explicitly implemented interfaces)
conversions. (No boxing, value type or user
conversions are allowed!)
● Try to limit the usage of array parameters to
param-arrays, as they are much safer.
● In C# no covariant return types are available (in
opposite to Java and C++).
● In C# methods with out and ref parameters are
also not variant on that parameters.
● Variance can only be declared on generic
interfaces and delegates, not on classes or
structs. => It does not work without explicitly
refactoring type hierarchies.
11. 11
Generic Interface Variance in Action
<CSharpCovariance>
This example shows generic interface variance in C#.
● No example dealing with generic variance on
delegates will be presented here. But you can
find some examples in the source code
accompanying this presentation.
12. 12
Summary: generic Variance
● What is generic interface/delegate variance?
– It allows "reasonable" implicit conversions between unrelated types to occur.
● So the main features variance enables are co- and contravariant conversions.
– It reduces the amount of compile time errors.
● But only reference conversions of return and parameter types can be used!
– (As with array covariance: no boxing, value type or user conversions are allowed!)
● Possibly you'll never code own variant types, but you'll exploit existing ones.
– Some .Net types have been made variant: IEnumerable<out T>/IEnumerator<out T>, IComparable<in T>, Action<in T, ...>,
Func<out T, in R, ..>, Converter<in T, out R>.
● Pitfalls with variant types:
– New implicit conversions are in avail: type checks and overloads behave differently.
– Generic variance on delegates does not work with multicasting.
● Example application: return types of factory
interfaces.
● Reference conversions: inheritance and interface
(of implicitly or explicitly implemented interfaces)
conversions.
● .Net collection types must stay invariant as they
use the same parametrized type for return and
parameter values.
● The problem with multicasting might be fixed with
a future .Net version.
● Before generic variance was enabled with C#4
there was a way to simulate covariance
(see:
http://blogs.msdn.com/b/kcwalina/archive/2008/0
4/02/simulatedcovariance.aspx
).
13. 13
Variance "Mechanics"
● Expressing generic variance on interfaces:
interface IFactory<out T>
{ // Covariant on T.
T Produce();
}
● Expressing generic variance on delegates:
// Covariant on T.
delegate T Func<out T>();
● Restrictions on expressing generic variance:
– Only interface and delegate variance is supported.
interface IAcceptor<in T>
{ // Contravariant on T.
void Accept(T t);
}
// Contravariant on T.
delegate void Action<in T>(T t);
– Due to guaranteed static type-safety, return types can only be covariant and parameter types can only be contravariant!
● You have to declare the variance on the type parameters explicitly!
● You can not express your own consistency, esp. no consistency can be expressed on exceptions.
– If T is a return type and a parameter type that type must be invariant.
– out method parameters are always invariant, as they are CLR ref parameters!
● The C# compiler could, at least in most cases, infer the
right variances; but you have to declare variances
explicitly, because it might lead to breaking code.
● Since exceptions are not part of signatures in C#, no
consistency can be declared on them.
● Because out method parameters can also be used to
pass data to a method they can not be safely covariant
as return types. The CLR does not make a difference
between out and ref parameters.
● In Java, variances are expressed on the caller side of
the (generic) type, i.e. nothing must be declared on the
type itself to act variant. - C# uses statically checked
definition-site variance (so does Scala).
● In dynamic languages the consistency is often present
intrinsically, because substitutability is not expressed
by static types, but by common interfaces (read: couple
of methods). - Subtyping instead of subclassing is used
here: more on this in following lectures.
● The IL syntax uses the symbols +/-T to denote the type
of variance (the Scala syntax is similar).