Fun with Lambdas: C++14 Style (part 1)Sumant Tambe
If virtual functions in C++ imply design patterns, then C++ lambdas imply what? What does it really mean to have lambdas in C++? Frankly, I don't know but I've a hunch: It's BIG.
Just like virtual functions open doors to the OO paradigm, lambdas open doors to a different paradigm--the functional paradigm. This talk is not a praise of functional programming or some elusive lambda-based library. (Although, I'll mention one briefly that tops my list these days.) Instead, the goal is to have fun while working our way through some mind-bending examples of C++14 lambdas. Beware, your brain will hurt! Bring your laptop and code the examples right along because that may be the fastest way to answer the quiz.
An introductory PowerPoint to understanding and applying the C++ programming language. Broken down into lessons covering:
Introduction: Definitions and the History of Programming
Lesson 1: Libraries, Variables and Types, Blocks and Namespaces, Functions
Lesson 2: If...Else Statements, For and While Loops, Scope
Exercise: Program a Gumball Game
Lesson 3: Classes and Objects, Pointers
Fun with Lambdas: C++14 Style (part 1)Sumant Tambe
If virtual functions in C++ imply design patterns, then C++ lambdas imply what? What does it really mean to have lambdas in C++? Frankly, I don't know but I've a hunch: It's BIG.
Just like virtual functions open doors to the OO paradigm, lambdas open doors to a different paradigm--the functional paradigm. This talk is not a praise of functional programming or some elusive lambda-based library. (Although, I'll mention one briefly that tops my list these days.) Instead, the goal is to have fun while working our way through some mind-bending examples of C++14 lambdas. Beware, your brain will hurt! Bring your laptop and code the examples right along because that may be the fastest way to answer the quiz.
An introductory PowerPoint to understanding and applying the C++ programming language. Broken down into lessons covering:
Introduction: Definitions and the History of Programming
Lesson 1: Libraries, Variables and Types, Blocks and Namespaces, Functions
Lesson 2: If...Else Statements, For and While Loops, Scope
Exercise: Program a Gumball Game
Lesson 3: Classes and Objects, Pointers
Sometimes you see code that is perfectly OK according to the definition of the language, but which is flawed because it breaks too many established idioms and conventions. On the other hand, a solid piece of code is something that looks like it is written by an experienced person who cares about professionalism in programming.
A presentation at Norwegian Developer Conference 2010
Slides from my "Gentle Introduction to Modern C++" presentation from January 20, 2015 at the Dublin C/C++ User Group: www.meetup.com/cppdug/events/219787667/
The code examples are located here: https://github.com/mihaitodor/Presentations/tree/master/cppdug/20.01.2015
The presentation shows major features of the new C++ standard (language and the library). The full list of new things is very broad, so I've categorized them to be easier to understand.
This presentation is an introduction to Dotty / Scala 3.
It covers the features which I deem most important for Scala developers.
For detailed information see the [Dotty documentation](https://dotty.epfl.ch/docs/index.html).
Virtual Functions support dynamic binding and object-oriented programming. A class that declares or inherits a virtual function is called a polymorphic class.
••• Learn how to safely manage memory with smart pointers! •••
In this presentation you will learn:
▸ the dangers of using raw pointers for dynamic memory
▸ the difference between unique_ptr, shared_ptr, weak_ptr
▸ how to use factories to increase safety and performance
▸ when raw pointers are still needed
(video of these slides available here http://fsharpforfunandprofit.com/fppatterns/)
In object-oriented development, we are all familiar with design patterns such as the Strategy pattern and Decorator pattern, and design principles such as SOLID.
The functional programming community has design patterns and principles as well.
This talk will provide an overview of some of these, and present some demonstrations of FP design in practice.
Sometimes you see code that is perfectly OK according to the definition of the language, but which is flawed because it breaks too many established idioms and conventions. On the other hand, a solid piece of code is something that looks like it is written by an experienced person who cares about professionalism in programming.
A presentation at Norwegian Developer Conference 2010
Slides from my "Gentle Introduction to Modern C++" presentation from January 20, 2015 at the Dublin C/C++ User Group: www.meetup.com/cppdug/events/219787667/
The code examples are located here: https://github.com/mihaitodor/Presentations/tree/master/cppdug/20.01.2015
The presentation shows major features of the new C++ standard (language and the library). The full list of new things is very broad, so I've categorized them to be easier to understand.
This presentation is an introduction to Dotty / Scala 3.
It covers the features which I deem most important for Scala developers.
For detailed information see the [Dotty documentation](https://dotty.epfl.ch/docs/index.html).
Virtual Functions support dynamic binding and object-oriented programming. A class that declares or inherits a virtual function is called a polymorphic class.
••• Learn how to safely manage memory with smart pointers! •••
In this presentation you will learn:
▸ the dangers of using raw pointers for dynamic memory
▸ the difference between unique_ptr, shared_ptr, weak_ptr
▸ how to use factories to increase safety and performance
▸ when raw pointers are still needed
(video of these slides available here http://fsharpforfunandprofit.com/fppatterns/)
In object-oriented development, we are all familiar with design patterns such as the Strategy pattern and Decorator pattern, and design principles such as SOLID.
The functional programming community has design patterns and principles as well.
This talk will provide an overview of some of these, and present some demonstrations of FP design in practice.
Powering Your Home was Phase II of the GE ecomagination Challenge, a $200 million innovation experiment where businesses, entrepreneurs, innovators and students shared their best ideas on how to improve our energy future. Phase II of the ecomagination Challenge focused on home energy with an open invitation for innovative ideas about capturing, managing, and using energy in the home. Ideas comments ptharso
Presentation by the BBC's Head of Audience Experience & Usability, Jonathan Hassell and Chris Rourke, MD of User Vision (www.uservision.co.uk) on the benefits of usability and accessibility research for the web, and other media platforms. Presented at Internet World, London, April 2009
Integrating Row Covers & Soil Amendments for Organic Cucumber Production; Gardening Guidebook for Iowa ~ Iowa State University~ For more information, Please see websites below:
`
Organic Edible Schoolyards & Gardening with Children =
http://scribd.com/doc/239851214 ~
`
Double Food Production from your School Garden with Organic Tech =
http://scribd.com/doc/239851079 ~
`
Free School Gardening Art Posters =
http://scribd.com/doc/239851159 ~
`
Increase Food Production with Companion Planting in your School Garden =
http://scribd.com/doc/239851159 ~
`
Healthy Foods Dramatically Improves Student Academic Success =
http://scribd.com/doc/239851348 ~
`
City Chickens for your Organic School Garden =
http://scribd.com/doc/239850440 ~
`
Huerto Ecológico, Tecnologías Sostenibles, Agricultura Organica
http://scribd.com/doc/239850233
`
Simple Square Foot Gardening for Schools - Teacher Guide =
http://scribd.com/doc/239851110
Session is about how to write first program in C#. Also discusses variables, Data Types, CTS, Value Type, Reference Type, string, object, dynamic, Type Casting, Boxing Unboxing, Console.ReadLine(), Console.WriteLine()
The final dream of every developer is creating his own programming language. Today it is possible to realize that dream with a reasonable effort. In addition to that is also possible to leverage the JVM to make a language that can reuse a huge amount of libraries. In this presentation we are going to see what elements do we need to build our own language, with a compiler for the JVM. This is not only a lot of fun but it can be also useful in practice, to build Domain Specific Languages that compiles to bytecode and can be used together with mainstream languages in larger applications.
A evolução da computação levou-nos até um ponto onde já não é possível,
como antigamente, aumentar a capacidade de processamento síncrono. A
evolução dos microprocessadores tem sido no sentido de aumentar o número de
unidades de processamento ao invés da capacidade de cada unidade.
A par disto, os nossos dados estão cada vez mais distribuídos e longe do
local de consumo e os utilizadores exigem cada vez mais melhores aplicações
e que respondam prementemente às suas interações criando a necessidade de
cada aplicação ter diversas componentes em execução concorrente.
Para dar respostas a estas novas necessidades, a linguagem de programação
C# disponibiliza novas instruções para facilitar a programação assíncrona.
O novo paradigma de aplicações com ligação à nuvem leva a que a latência das comunicações seja maior do que aplicações totalmente locais. Para auxiliar o desenvolvimento deste novo paradigma, a última versão do C# 5.0 faz com que programação assíncrona pareça tão fácil como a programação síncrona.
Nesta sessão, o Paulo irá apresentar as novas funcionalidades do C# 5.0 no .NET Framework 4.5, com demonstrações práticas de utilização de cada uma das funcionalidades.
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
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/
Let's dive deeper into the world of ODC! Ricardo Alves (OutSystems) will join us to tell all about the new Data Fabric. After that, Sezen de Bruijn (OutSystems) will get into the details on how to best design a sturdy architecture within ODC.
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.
"Impact of front-end architecture on development cost", Viktor TurskyiFwdays
I have heard many times that architecture is not important for the front-end. Also, many times I have seen how developers implement features on the front-end just following the standard rules for a framework and think that this is enough to successfully launch the project, and then the project fails. How to prevent this and what approach to choose? I have launched dozens of complex projects and during the talk we will analyze which approaches have worked for me and which have not.
Search and Society: Reimagining Information Access for Radical FuturesBhaskar Mitra
The field of Information retrieval (IR) is currently undergoing a transformative shift, at least partly due to the emerging applications of generative AI to information access. In this talk, we will deliberate on the sociotechnical implications of generative AI for information access. We will argue that there is both a critical necessity and an exciting opportunity for the IR community to re-center our research agendas on societal needs while dismantling the artificial separation between the work on fairness, accountability, transparency, and ethics in IR and the rest of IR research. Instead of adopting a reactionary strategy of trying to mitigate potential social harms from emerging technologies, the community should aim to proactively set the research agenda for the kinds of systems we should build inspired by diverse explicitly stated sociotechnical imaginaries. The sociotechnical imaginaries that underpin the design and development of information access technologies needs to be explicitly articulated, and we need to develop theories of change in context of these diverse perspectives. Our guiding future imaginaries must be informed by other academic fields, such as democratic theory and critical theory, and should be co-developed with social science scholars, legal scholars, civil rights and social justice activists, and artists, among others.
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
The publishing industry has been selling digital audiobooks and ebooks for over a decade and has found its groove. What’s changed? What has stayed the same? Where do we go from here? Join a group of leading sales peers from across the industry for a conversation about the lessons learned since the popularization of digital books, best practices, digital book supply chain management, and more.
Link to video recording: https://bnctechforum.ca/sessions/selling-digital-books-in-2024-insights-from-industry-leaders/
Presented by BookNet Canada on May 28, 2024, with support from the Department of Canadian Heritage.
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.
Neuro-symbolic is not enough, we need neuro-*semantic*Frank van Harmelen
Neuro-symbolic (NeSy) AI is on the rise. However, simply machine learning on just any symbolic structure is not sufficient to really harvest the gains of NeSy. These will only be gained when the symbolic structures have an actual semantics. I give an operational definition of semantics as “predictable inference”.
All of this illustrated with link prediction over knowledge graphs, but the argument is general.
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/
17. In multilinear algebra and tensor analysis, covariance and contravariance describe how the quantitative description of certain geometrical or physical entities changes when passing from one coordinate system to another. Wikipedia Covariance And Contravarance
18. Type Tis greater than (>) type Sif Sis a subtype of (derives from) T Covariance And Contravarance T≥S typeof(T).IsAssignableFrom(typeof(S))
19. Give 2 types Base and Derived, such that: There is a reference (or identity) conversion between Base and Derived Base ≥ Derived A generic type definition Generic<T> is: Covariant in T If Genérico<Base> ≥ Genérico<Derived> Contravariant in T If Genérico<Base> ≤ Genérico<Derived> Invariant in T If neither of the above apply Covariance And Contravarance
20. Contravariante em T Covariante em T typeof(Base).IsAssignableFrom(typeof(Derived)) typeof(Base).IsAssignableFrom(typeof(Derived)) typeof(G<Derived>).IsAssignableFrom(typeof(G<Base>)) typeof(G<Base>).IsAssignableFrom(typeof(G<Derived>)) Covariance And Contravarance
21. Covariance And Contravarance C# (.NET) arrays are covariant string[] strings = GetStringArray(); Process(strings); … but not safely covariant void Process(object[] objects) { … } void Process(object[] objects) { objects[0] = "Hello"; // Ok objects[1] = newButton(); // Exception! }
22. Covariance And Contravarance Until now, C# (.NET) generics have been invariant List<string> strings = GetStringList(); Process(strings); C# 4.0 supports safe covariance and contravariance void Process(IEnumerable<object> objects) { // IEnumerable<T> is read-only and // therefore safely covariant } void Process(IEnumerable<object> objects) { … }
23. Safe Covariance out= covariant Output positions only publicinterfaceIEnumerable<T> { IEnumerator<T> GetEnumerator(); } publicinterfaceIEnumerable<out T> { IEnumerator<T> GetEnumerator(); } Can be treated as less derived publicinterfaceIEnumerator<T> { T Current { get; } boolMoveNext(); } publicinterfaceIEnumerator<out T> { T Current { get; } boolMoveNext(); } IEnumerable<string> strings = GetStrings(); IEnumerable<object> objects = strings;
24. Safe Contravariance in= contravariantInput positions only Can be treated as more derived publicinterfaceIComparer<T> { int Compare(T x, T y); } publicinterfaceIComparer<in T> { int Compare(T x, T y); } IComparer<object> objComp = GetComparer(); IComparer<string> strComp = objComp;
25. Supported for generic interface and delegate types only. Verified/enforced staticaliy in the definition. Value types are always invariant IEnumerable<int> is not IEnumerable<object> Similar to existing rules for arrays ref and out parameters need invariant types Variance In C# 4.o
27. Covariance And Contravariance In Generics http://paulomorgado.net/en/blog/archive/2010/04/13/c-4-0-covariance-and-contravariance-in-generics.aspx Covariance And Contravariance In Generics Made Easy http://paulomorgado.net/en/blog/archive/2010/04/15/c-4-0-covariance-and-contravariance-in-generics-made-easy.aspx Covarince and Contravariance in Generics http://msdn.microsoft.com/library/dd799517(VS.100).aspx Exact rules for variance validity http://blogs.msdn.com/ericlippert/archive/2009/12/03/exact-rules-for-variância-validity.aspx Events get a little overhaul in C# 4, Afterward: Effective Events http://blogs.msdn.com/cburrows/archive/2010/03/30/events-get-a-little-overhaul-in-c-4-afterward-effective-events.aspx Resources
29. Named And Optional Arguments Greeting("Mr.", "Morgado", 42); Parameters Arguments public void Greeting(string title, string name, intage) They always have names They are never optional
30. Named Arguments int i = 0; Method(i, third: i++, second: ++i); int i = 0; int CS$0$0000 = i++; int CS$0$0001 = ++i; Method(i, CS$0$0001, CS$0$0000); public void Method(intfirst, intsecond, intthird)
31. Optional Arguments int i = 0; Method(i, third: ++i); int i = 0; int CS$0$0000 = ++i; Method(i, 2, CS$0$0000); public void Method(intfirst, intsecond = 5, intthird = 6) public void Method(intfirst, intsecond = 2, intthird = 3) public void Method(intfirst, intsecond) They look like overloads. But they aren’t! public void Method(intfirst)
33. C# 4.0: Named And Optional Arguments http://paulomorgado.net/en/blog/archive/2010/04/16/c-4-0-named-and-optional-arguments.aspx C# 4.0: Alternative To Optional Arguments http://paulomorgado.net/en/blog/archive/2010/04/18/c-4-0-alternative-to-optional-arguments.aspx Named and Optional Arguments (C# Programming Guide) http://msdn.microsoft.com/library/dd264739(VS.100).aspx Resources
40. IDynamicMetaObjectProvider Represents a dynamic object that can have operations determined at run-time. DynamicObject : IDynamicMetaObjectProvider Enables you to define which operations can be performed on dynamic objects and how to perform those operations. ExpandoObject : IDynamicMetaObjectProvider Enables you to add and delete members of its instances at run time and also to set and get values of these members. Building Dynamic Objects
41. Dynamic Programming http://paulomorgado.net/en/blog/archive/2010/04/18/c-4-0-dynamic-programming.aspx C# Proposal: Compile Time Static Checking Of Dynamic Objects http://paulomorgado.net/en/blog/archive/2010/03/19/c-proposal-compile-time-static-checking-of-dynamic-objects.aspx Using Type dynamic (C# Programming Guide) http://msdn.microsoft.com/library/dd264736(VS.100).aspx Dynamic Language Runtime Overview http://msdn.microsoft.com/library/dd233052(v=VS.100).aspx Resources
43. Named and optional arguments Ommiting ref Dynamic Import Automatic mapping object -> dynamic Indexed properties Type Equivalence And Type Embedding (“NO PIA”) COM Interop Improvements
47. COM Interop Improvements http://paulomorgado.net/en/blog/archive/2010/04/19/c-4-0-com-interop-improvements.aspx Type Equivalence and Embedded InteropTypes http://msdn.microsoft.com/library/dd997297.aspx Resources
The first release of C# (C# 1.0) was all about building a new language for managed code that appealed, mostly, to C++ and Java programmers.The second release (C# 2.0) was mostly about adding what wasn’t time to built into the 1.0 release. The main feature for this release was Generics.The third release (C# 3.0) was all about reducing the impedance mismatch between general purpose programming languages and databases. To achieve this goal, several functional programming features were added to the language and LINQ was born.
Going forward, new trends are showing up in the industry and modern programming languages need to be more:DeclarativeWith imperative languages, although having the eye on the what, programs need to focus on the how. This leads to over specification of the solution to the problem in hand, making next to impossible to the execution engine to be smart about the execution of the program and optimize it to run it more efficiently (given the hardware available, for example).Declarative languages, on the other hand, focus only on the what and leave the how to the execution engine. LINQ made C# more declarative by using higher level constructs like orderby and group by that give the execution engine a much better chance of optimizing the execution (by parallelizing it, for example).ConcurrentConcurrency is hard and needs to be thought about and it’s very hard to shoehorn it into a programming language. Parallel.For (from the parallel extensions) looks like a parallel for because enough expressiveness has been built into C# 3.0 to allow this without having to commit to specific language syntax.DynamicThere was been lots of debate on which ones are the better programming languages: static or dynamic. The fact is that both have good qualities and users of both types of languages want to have it all.All these trends require a paradigm switch. C# is, in many ways, already a multi-paradigm language. It’s still very object oriented (class oriented as some might say) but it can be argued that C# 3.0 has become a functional programming language because it has all the cornerstones of what a functional programming language needs. Moving forward, will have even more.
All these trends require a paradigm switch. C# is, in many ways, already a multi-paradigm language. It’s still very object oriented (class oriented as some might say) but it can be argued that C# 3.0 has become a functional programming language because it has all the cornerstones of what a functional programming language needs. Moving forward, will have even more.Besides the influence of these trends, there was a decision of co-evolution of the C# and Visual Basic programming languages. Since its inception, there was been some effort to position C# and Visual Basic against each other and to try to explain what should be done with each language or what kind of programmers use one or the other. Each language should be chosen based on the past experience and familiarity of the developer/team/project/company and not by particular features.In the past, every time a feature was added to one language, the users of the other wanted that feature too. Going forward, when a feature is added to one language, the other will work hard to add the same feature. This doesn’t mean that XML literals will be added to C# (because almost the same can be achieved with LINQ To XML), but Visual Basic will have auto-implemented properties.Most of these features require or are built on top of features of the .NET Framework and, the focus for C# 4.0 was on dynamic programming. Not just dynamic types but being able to talk with anything that isn’t a .NET class.Also introduced in C# 4.0 is co-variance and contra-variance for generic interfaces and delegates.
C# 4.0 (and .NET 4.0) introduced covariance and contravariance to generic interfaces and delegates. But what is this variance thing?According to Wikipedia, in multilinear algebra and tensor analysis, covariance and contravariance describe how the quantitative description of certain geometrical or physical entities changes when passing from one coordinate system to another.(*)
But what does this have to do with C# or .NET?In type theory, a the type T is greater (>) than type S if S is a subtype (derives from) T, which means that there is a quantitative description for types in a type hierarchy.So, how does covariance and contravariance apply to C# (and .NET) generic types?
In C# (and .NET), variance is a relation between a generic type definition and a particular generic type parameter.Given two types Base and Derived, such that:There is a reference (or identity) conversion between Base and DerivedBase ≥ DerivedA generic type definition Generic<T> is:covariant in T if the ordering of the constructed types follows the ordering of the generic type parameters: Generic<Base> ≥ Generic<Derived>. contravariant in T if the ordering of the constructed types is reversed from the ordering of the generic type parameters: Generic<Base> ≤ Generic<Derived>. invariant in T if neither of the above apply.
If this definition is applied to arrays, we can see that arrays have always been covariant in relation to the type of the elements because this is valid code:object[] objectArray = new string[] { "string 1", "string 2" };objectArray[0] = "string 3";objectArray[1] = new object();However, when we try to run this code, the second assignment will throw an ArrayTypeMismatchException. Although the compiler was fooled into thinking this was valid code because an object is being assigned to an element of an array ofobject, at run time, there is always a type check to guarantee that the runtime type of the definition of the elements of the array is greater or equal to the instance being assigned to the element. In the above example, because the runtime type of the array is array of string, the first assignment of array elements is valid because string ≥ string and the second is invalid because string ≤ object.This leads to the conclusion that, although arrays have always been covariant in relation to the type of the elements, they are not safely covariant – code that compiles is not guaranteed to run without errors.
In C#, variance is enforced in the declaration of the type and not determined by the usage of each the generic type parameter.Covariance in relation to a particular generic type parameter is enforced, is using the out generic modifier.Notice the convenient use the pre-existing out keyword. Besides the benefit of not having to remember a new hypothetic covariant keyword, out is easier to remember because it defines that the generic type parameter can only appear in output positions — read-only properties and method return values.
In a similar way, the way contravariance is enforced in relation a particular generic type parameter, is using the in generic modifier.Once again, the use of the pre-existing in keyword makes it easier to remember that the generic type parameter can only be used in input positions — write-only properties and method non ref and non out parameters.
A generic type parameter that is not marked covariant (out) or contravariant (in) is invariant.Because covariance and contravariance applies to the relation between a generic type definition and a particular generic type parameter, a generic type definition can be both covariant, contravariant and invariant depending on the generic type parameter.In the above delegate definition, Func<T, TResult> is contravariant in T and convariant in TResult.All the types in the .NET Framework where variance could be applied to its generic type parameters have been modified to take advantage of this new feature.In summary, the rules for variance in C# (and .NET) are:Variance in relation to generic type parameters is restricted to generic interface and generic delegate type definitions.A generic interface or generic delegate type definition can be covariant, contravariant or invariant in relation to different generic type parameters.Variance applies only to reference types: a IEnumerable<int> is not an IEnumerable<object>.Variance does not apply to delegate combination. That is, given two delegates of types Action<Derived> and Action<Base>, you cannot combine the second delegate with the first although the result would be type safe. Variance allows the second delegate to be assigned to a variable of type Action<Derived>, but delegates can combine only if their types match exactly.If you want to learn more about variance in C# (and .NET), you can always read:Covariance and Contravariance in Generics — MSDN LibraryExact rules for variance validity — Eric LippertEvents get a little overhaul in C# 4, Afterward: Effective Events — Chris BurrowsNote: Because variance is a feature of .NET 4.0 and not only of C# 4.0, all this also applies to Visual Basic 10.
As part of the co-evolution effort of C# and Visual Basic, C# 4.0 introduces Named and Optional Arguments.First of all, let’s clarify what are arguments and parameters:Method definition parameters are the input variables of the method.Method call arguments are the values provided to the method parameters.In fact, the C# Language Specification states the following on §7.5:The argument list (§7.5.1) of a function member invocation provides actual values or variable references for the parameters of the function member.Given the above definitions, we can state that:Parameters have always been named and still are.Parameters have never been optional and still aren’t.
Until now, the way the C# compiler matched method call definition arguments with method parameters was by position. The first argument provides the value for the first parameter, the second argument provides the value for the second parameter, and so on and so on, regardless of the name of the parameters. If a parameter was missing a corresponding argument to provide its value, the compiler would emit a compilation error.For this call:Greeting("Mr.", "Morgado", 42); this method:public void Greeting(string title, string name, intage)will receive as parameters:title: “Mr.”name: “Morgado”age: 42What this new feature allows is to use the names of the parameters to identify the corresponding arguments in the form: name:valueNot all arguments in the argument list must be named. However, all named arguments must be at the end of the argument list. The matching between arguments (and the evaluation of its value) and parameters will be done first by name for the named arguments and than by position for the unnamed arguments.This means that, for this method definition:public void Method(intfirst, intsecond, intthird) this call declaration:inti = 0; Method(i, third: i++, second: ++i); will have this code generated by the compiler:inti = 0; intCS$0$0000 = i++; intCS$0$0001 = ++i; Method(i, CS$0$0001, CS$0$0000); which will give the method the following parameter values:first: 2 second: 2 third: 0 Notice the variable names. Although invalid being invalid C# identifiers, they are valid .NET identifiers and thus avoiding collision between user written and compiler generated code.Besides allowing to re-order of the argument list, this feature is very useful for auto-documenting the code, for example, when the argument list is very long or not clear, from the call site, what the arguments are.
Parameters can now have default values:public void Method(intfirst, intsecond = 2, intthird = 3) Parameters with default values must be the last in the parameter list and its value is used as the value of the parameter if the corresponding argument is missing from the method call declaration.For this call declaration:inti = 0; Method(i, third: ++i); will have this code generated by the compiler:inti = 0; intCS$0$0000 = ++i; Method(i, 2, CS$0$0000); which will give the method the following parameter values:first: 1 second: 2 third: 1 Because, when method parameters have default values, arguments can be omitted from the call declaration, this might seem like method overloading or a good replacement for it, but it isn’t.Although methods like this:public StreamReaderOpenTextFile(string path,Encoding encoding = null,booldetectEncoding = true,intbufferSize = 1024) allow to have its calls written like this:OpenTextFile("foo.txt", Encoding.UTF8); OpenTextFile("foo.txt", Encoding.UTF8, bufferSize: 4096); OpenTextFile(bufferSize: 4096, path: "foo.txt",detectEncoding: false); The complier handles default values like constant fields taking the value and useing it instead of a reference to the value. So, like with constant fields, methods with parameters with default values are exposed publicly (and remember that internal members might be publicly accessible – InternalsVisibleToAttribute). If such methods are publicly accessible and used by another assembly, those values will be hard coded in the calling code and, if the called assembly has its default values changed, they won’t be assumed by already compiled code.At the first glance, I though that using optional arguments for “bad” written code was great, but the ability to write code like that was just pure evil. But than I realized that, since I use private constant fields, it’s OK to use default parameter values on privately accessed methods.
Like I mentioned in my last post, exposing publicly methods with optional arguments is a bad practice (that’s why C# has resisted to having it, until now).You might argument that your method or constructor has to many variants and having ten or more overloads is a maintenance nightmare, and you’re right. But the solution has been there for ages: have an arguments class.The arguments class pattern is used in the .NET Framework is used by several classes, like XmlReader and XmlWriter that use such pattern in their Create methods, since version 2.0:XmlReaderSettingssettings = new XmlReaderSettings(); settings.ValidationType = ValidationType.Auto; XmlReader.Create("file.xml", settings); With this pattern, you don’t have to maintain a long list of overloads and any default values for properties of XmlReaderSettings (or XmlWriterSettings for XmlWriter.Create) can be changed or new properties added in future implementations that won’t break existing compiled code.You might now argue that it’s too much code to write, but, with object initializers added in C# 3.0, the same code can be written like this:XmlReader.Create("file.xml", new XmlReaderSettings{ ValidationType = ValidationType.Auto }); Looks almost like named and optional arguments, doesn’t it? And, who knows, in a future version of C#, it might even look like this:XmlReader.Create("file.xml", new { ValidationType = ValidationType.Auto });
The major feature of C# 4.0 is dynamic programming. Not just dynamic typing, but dynamic in broader sense, which means talking to anything that is not statically typed to be a .NET object.Dynamic Language RuntimeThe Dynamic Language Runtime (DLR) is piece of technology that unifies dynamic programming on the .NET platform, the same way the Common Language Runtime (CLR) has been a common platform for statically typed languages.The CLR always had dynamic capabilities. You could always use reflection, but its main goal was never to be a dynamic programming environment and there were some features missing. The DLR is built on top of the CLR and adds those missing features to the .NET platform.The Dynamic Language Runtime is the core infrastructure that consists of:Expression TreesThe same expression trees used in LINQ, now improved to support statements.Dynamic DispatchDispatches invocations to the appropriate binder.Call Site CachingFor improved efficiency.Dynamic languages and languages with dynamic capabilities are built on top of the DLR. IronPython and IronRuby were already built on top of the DLR, and now, the support for using the DLR is being added to C# and Visual Basic. Other languages built on top of the CLR are expected to also use the DLR in the future.Underneath the DLR there are binders that talk to a variety of different technologies:.NET BinderAllows to talk to .NET objects.JavaScript BinderAllows to talk to JavaScript in SilverLight.IronPython BinderAllows to talk to IronPython.IronRuby BinderAllows to talk to IronRuby.COM BinderAllows to talk to COM.Whit all these binders it is possible to have a single programming experience to talk to all these environments that are not statically typed .NET objects.
Let’s take this traditional statically typed code:Calculator calculator = GetCalculator(); intsum = calculator.Sum(10, 20); Because the variable that receives the return value of the GetCalulator method is statically typed to be of type Calculator and, because the Calculator type has an Add method that receives two integers and returns an integer, it is possible to call that Sum method and assign its return value to a variable statically typed as integer.Now lets suppose the calculator was not a statically typed .NET class, but, instead, a COM object or some .NET code we don’t know he type of. All of the sudden it gets very painful to call the Add method:object calculator = GetCalculator(); Type calculatorType = calculator.GetType(); object res = calculatorType.InvokeMember("Add", BindingFlags.InvokeMethod, null, calculator, new object[] { 10, 20 }); intsum = Convert.ToInt32(res); And what if the calculator was a JavaScript object?ScriptObjectcalculator = GetCalculator(); object res = calculator.Invoke("Add", 10, 20); intsum = Convert.ToInt32(res); For each dynamic domain we have a different programming experience and that makes it very hard to unify the code.With C# 4.0 it becomes possible to write code this way:dynamic calculator = GetCalculator(); intsum = calculator.Add(10, 20); You simply declare a variable who’s static type is dynamic. dynamic is a pseudo-keyword (like var) that indicates to the compiler that operations on the calculator object will be done dynamically.The way you should look at dynamic is that it’s just like object (System.Object) with dynamic semantics associated. Anything can be assigned to a dynamic.
At run-time, all object will have a type. In the above example x is of type System.Int32.When one or more operands in an operation are typed dynamic, member selection is deferred to run-time instead of compile-time. Then the run-time type is substituted in all variables and normal overload resolution is done, just like it would happen at compile-time.
The result of any dynamic operation is always dynamic and, when a dynamic object is assigned to something else, a dynamic conversion will occur.double x = 1.75; double y = Math.Abs(x);Compile-timedouble Abs(double x)dynamic x = 1.75; dynamic y = Math.Abs(x);Run-timedouble Abs(double x)dynamic x = 2; dynamic y = Math.Abs(x);Run-timeint Abs(int x)The above code will always be strongly typed. The difference is that, in the first case the method resolution is done at compile-time, and the others it’s done ate run-time.
The DLR is pre-wired to know .NET objects, COM objects and so forth but any dynamic language can implement their own objects or you can implement your own objects in C# through the implementation of the IDynamicMetaObjectProvider interface. When an object implements IDynamicMetaObjectProvider, it can participate in the resolution of how method calls and property access is done.The .NET Framework already provides two implementations of IDynamicMetaObjectProvider:DynamicObject : IDynamicMetaObjectProviderThe DynamicObject class enables you to define which operations can be performed on dynamic objects and how to perform those operations. For example, you can define what happens when you try to get or set an object property, call a method, or perform standard mathematical operations such as addition and multiplication.ExpandoObject : IDynamicMetaObjectProviderThe ExpandoObject class enables you to add and delete members of its instances at run time and also to set and get values of these members. This class supports dynamic binding, which enables you to use standard syntax like sampleObject.sampleMember, instead of more complex syntax like sampleObject.GetAttribute("sampleMember").
Dynamic resolution as well as named and optional arguments greatly improve the experience of interoperating with COM APIs such as Office Automation Primary Interop Assemblies (PIAs). But, in order to alleviate even more COMInterop development, a few COM-specific features were also added to C# 4.0.
Because of a different programming model, many COM APIs contain a lot of reference parameters. These parameters are typically not meant to mutate a passed-in argument, but are simply another way of passing value parameters.Specifically for COM methods, the compiler allows to declare the method call passing the arguments by value and will automatically generate the necessary temporary variables to hold the values in order to pass them by reference and will discard their values after the call returns. From the point of view of the programmer, the arguments are being passed by value.
Dynamic ImportMany COM methods accept and return variant types, which are represented in the PIAs as object. In the vast majority of cases, a programmer calling these methods already knows the static type of a returned object form the context of the call, but has to explicitly perform a cast on the returned values to make use of that knowledge. These casts are so common that they constitute a major nuisance.To make the developer’s life easier, it is now possible to import the COM APIs in such a way that variants are instead represented using the type dynamic which means that COM signatures have now occurrences of dynamic instead of object.This means that members of a returned object can now be easily accessed or assigned into a strongly typed variable without having to cast.Indexed And Default PropertiesA few COM interface features are still not available in C#. On the top of the list are indexed properties and default properties. As mentioned above, these will be possible if the COM interface is accessed dynamically, but will not be recognized by statically typed C# code.
For assemblies indentified with PrimaryInteropAssemblyAttribute, the compiler will create equivalent types (interfaces, structs, enumerations and delegates) and embed them in the generated assembly.To reduce the final size of the generated assembly, only the used types and their used members will be generated and embedded.Although this makes development and deployment of applications using the COM components easier because there’s no need to deploy the PIAs, COM component developers are still required to build the PIAs.