SlideShare une entreprise Scribd logo
1  sur  13
Télécharger pour lire hors ligne
1
Nico Ludwig (@ersatzteilchen)
New C#4 Features – Part I
2
TOC
● New C#4 Features – Part I
– Focus of C#4 Features
– Simplifications in Syntax
– Simplifications for Working with COM
– Improvements in Code Generation
● Sources:
– Jon Skeet, CSharp in Depth
3
Focus of C#4
● Interoperability (basically not new CLR 4 features):
– Enhancements for COM interoperability and PIA.
– Dynamic typing and the Dynamic Language Runtime (DLR).
● VB and C# co/evolution (already in the CLR 1 and 2, now enabled in C#4):
– Optional parameters, named arguments.
– Configurable generic co- and contravariance for parameter and return types.
● Performance (new features in the CLR 4):
– New threading model (esp. addressing thread pools and the gc).
– Parallel extensions (Task Parallel Library (TPL), the types Task and Parallel, PLINQ).
● Code Quality:
– Code Contracts
● Dynamic typing enables easy usage of COM types
(e.g. Microsoft Office automation) and
dynamic/scripting languages (IronRuby,
IronPython).
● The CLR didn’t need to change in order to enable
the DLR.
● PLINQ is implemented as a set of extension
methods on ParallelQuery/<T>.
4
Named Arguments
● Positional and named arguments can be used as alternatives or in combination.
● It can enhance readability.
● (Good if certain parameters often change their position in declarations.)
● The names of formal parameters are now part of a type's public interface in C#.
– .Net/CLR supported named arguments from the start.
// Positional argument passing in C#1/C#2/C#3:
anInstance.AMethod(42, 21);
// New in C#4: named argument passing:
anInstance.AMethod(foo: 42, bar: 21);
/* or: */
anInstance.AMethod(bar: 21, foo: 42);
// Let's assume that we'd like to call following method:
public void AMethod(int foo, int bar) { /* pass */ }
● Named arguments are present in VB for a long
time. Smalltalk and Objective-C use a combination
of positional and named argument passing for all
method calls. In CLOS there exist so-called
"keywords" that work similar to named argument
passing.
● Being part of the public interface means:
● Changing the name of a parameter could break
calling code at compile time. We can circumvent
this by avoiding the usage of named parameters
or by avoiding to change the names of the
parameters on public, or protected methods.
5
Named Arguments and optional Parameters in Action
<NamedArgumentsAndOptionalParameters>
Presents named arguments and optional parameters.
● These features will be shown in one example,
because we will encounter them together in
practice very often.
● Parameter: The variable being declared in the
declaration of a function or method.
● Argument: The expression passed to a function or
method.
6
Optional Parameters
● Make parameters optional by specification of a default value constant.
– Can be used with almost all kinds of methods (incl. interfaces' methods).
– Reduces the need for overloads.
● The CLR supported them from the start (via the OptionalAttribute).
– Optional parameters are CLS compliant, but...
● The default values are compile time bound (like the resolution of overloads).
– Can cause version problems similar to public constants. - Callers must recompile!
– Prevent version problems: named arguments, overloads or value reinterpretation.
// This method can be called this way:
anInstance.DoSomething(42, 56);
/* or this way: */
anInstance.DoSomething(42);
// C#4's new syntax to declare a method having an optional parameter "bar":
public void DoSomething(int foo, int bar = 0) { /* pass */ }
●
Optional parameters were present in VB before it was a .Net language (often
used as hack to simulate non-existing overloads in earlier versions of VB).
●
Exactly as for constants the optional parameters' values are stored in the
metadata of the assembly, thus we can only use primitive types.
● The default values need to be compile time constants: literals, incl. null (i.e.
default(<ReferenceType>)) or any parameterless ctor of a value type (i.e.
default(<ValueType>)) or const members or enum values; an implicit
conversion to the parameter type must be existent (not a user defined
conversion). For empty strings we have to use "" rather than string.Empty,
because later is not a compile time constant but a static property. The
restrictions are similar to custom attribute values.
● If we run the code analysis (CA) against code using optional parameters we'll
get the warning CA1026 "Default parameters should not be used". Overloads
are considered the better feature, because languages w/o optional parameter
support need to pass all parameters. - The CA says: better avoid it (after the
Framework Design Guidelines 5.1.1).
● The usage of optional parameters in internal and private methods is ok.
●
To be frank there is one important advantage: optional parameters are itself a
good documentation.
● Optional parameters seem to be similar to default arguments in C++. But
they're not. In C++ default arguments don't need to be compile time constants.
But in C++ we also have to recompile all callers of a function/method, if a
default argument is a compile time constant and has been modified. Mind that
in C++ we _have to recompile_ to do this, because the modification has then
been done in an h-file (due to separated compilation); and whenever a h-file
has changed _each_ includer must recompile. - Such a dependency isn't
existing in C#, but recompilation against modified APIs comes into play when
any public compile time constant has been changed.
● Optional parameters carry the "defaultvalue" attribute in COM.
7
Another practical Example: Value Interpretation
<NamedArgumentsAndOptionalParameters>
Solving versioning problems with value interpretation.
8
CLS Site of Named Arguments and Optional Parameters
● Default values of methods with optional parameters are stored on the caller site.
– We can inspect the caller site (e.g. with Reflector) to see the default values (in IL code).
– If the default value was modified, all callers need to recompile to get the new value.
– If the callers don't recompile they will continue to use the previous default parameter.
– Adding new optional parameters to public/protected methods will break at run time, if callers don't recompile!
– => In effect methods can go silently incompatible! This is the versioning problem.
– A ctor having only optional parameters is not accepted as parameterless ctor (dctor)!
– (Method overloads are more robust than optional parameters.)
● The names of named arguments are stored on the caller site.
– If a parameter's name was modified, formerly compiled callers will continue to work.
– If a caller then tries to recompile, it needs to rename the named arguments respectively.
– => Renamed parameters are only a breaking change on compile time afterwards.
● Method calls to methods with optional arguments
can't be done in expression trees, if no arguments
are passed.
● The break at run time does only happen, if a method
of a referenced assembly was modified.
Modifications in the same assembly can go really
silently incompatible by using wrong or "shifted"
default values.
● The versioning problem mentioned before is not
existing when using overloads instead of optional
parameters. Optional parameters couple the caller
tighter than overloads.
● In C++ a ctor only having parameters with default
arguments is automatically also a dctor.
● To make the versioning problem visible we can force
developers to recompile their code, e.g. if we make
the interface deliberately incompatible.
9
Summary: Named Arguments and Optional Parameters
● Enable features in C# that were already present in the CLR.
● Its combination is useful.
– Esp. to reduce the noisiness of APIs like COM automation (more to come later).
● Can be used to with almost any kind of method (also ctors and indexers).
– Can not be used to implement/call operator methods.
● Influence resolving of method overloads.
– Named arguments may reduce the count of candidates on resolving.
– Optional parameters may increase the count of candidates on resolving.
● These features were introduced into C# to improve the support of COM.
● Usefulness of the combination of named arguments and optional
parameters:
● Named arguments and optional parameters can save 15 overloads of a
four-parameter method!
● There exist MS Office APIs with up to 16 parameters! - We don't need
to pass ten Type.Missing arguments and to fill the other six arguments
with meaningful arguments, instead we just exploit the combination of
named argument passing and optional parameters.
● C#'s indexers aren't operators. They aren't static methods and they can
be defined with another arity.
● (In C++ the subscript operator can only be binary. However the function
call operator can have any arity and can, as the only operator in C++,
have default arguments.)
● Indexers can have default arguments, but it makes only sense having
indexers with more than one parameter, because we can't directly call an
indexer w/o specifying at least one argument in C#.
● Named arguments reduce the count of candidates, because only
overloads having parameters with exactly the written names will be
considered.
● Optional arguments increase the count of candidates, because some
methods could have more parameters than the number of passed
arguments.
● Named arguments and optional parameters are similar to positional and
named parameters in .Net custom attributes.
10
COM Interop Improvements in Action
<EvolutionOfComInteropImprovements>
This example presents some Microsoft specific simplifications for COM
interoperability.
"COM is not dead, it is done!" Don Box, Nov. 2003
11
Summary: Simplifications for Working with COM
● I.e. simplifications for generated code of interop assemblies.
● COM does not support method overloads, so many parameters (and arguments) are required.
– Optional parameters and named arguments come in handy...
– ... in fact they have been introduced into C# only to support better COM interop.
● Almost all parameters in COM interfaces are ref parameters.
– Values (e.g. literals) can be directly passed as arguments to ref parameters.
● One more simplification: Named indexers can be called easily.
● No-PIA deployment: PIA code can now be linked in instead of only referenced.
– Only the used types will be linked/embedded into our resulting assembly.
– Self contained assemblies have a smaller "footprint" and reduce version problems.
● Mind that the simplifications shown in this section are highly
Microsoft dependent.
● E.g. there exist MS Office COM APIs with up to 16 parameters!
● The usage of ref parameters in COM is due to performance gains
(often seen with VARIANTs that must be passed as plain objects).
Typically the arguments aren't modified within these COM methods.
● Named indexers can only be called in C#, but we can't define new
ones. (These so called "indexed properties" are known in the CLR
and applicable in VB since .Net1. The unnamed indexed property
(i.e. the "indexer") present in C# is called "default property/member".)
● Named indexers in generated interop code, that only have optional
arguments, can also be called from C#.
● No-PIA deployment bases on .Net 4's new feature "type
equivalence". It allows the run time to consider certain types as being
interchangeable even if they are defined in different assemblies, so it
enhances interoperability. The idea of PIA was that only one
assembly contains all the types, this was relaxed with type
equivalence. Every linked-in copy of the type gets a TypeIdentifier
attribute that declares equivalent types with a common identifier (not
for types with behavior, only interfaces, delegates, enums and
PODs).
● No-PIA deployed types will enable dynamic coding that simplifies
working with COM (esp. with IDispatch and VARIANTs) even further.
This will be discussed in a later lecture...
12
Improvements in Code Generation
● Some less prominent changes for thread-safety made their way into C#4.
● The lock statement's implementation got more robust.
– The generated code uses monitors in a thread-safe and exception-safe fashion.
● Field-like events' implementation got more robust.
– The this reference or the type of the surrounding type won't be locked any longer.
● Instead on add/remove an atomic Interlocked.CompareExchange<T>()-call is used.
– The +=/-= operators will always be performed on the event field.
●
Also within the declaring class. Before C#3 it was performed on the backing field directly!
● This was done to exploit the gained thread-safety as explained above (read: atomicity).
● (On other operations (assignment/call), the backing field will still be used directly.)
13
Thank you!

Contenu connexe

Tendances

C#3.0 & Vb 9.0 New Features
C#3.0 & Vb 9.0 New FeaturesC#3.0 & Vb 9.0 New Features
C#3.0 & Vb 9.0 New Features
techfreak
 
Different phases of a compiler
Different phases of a compilerDifferent phases of a compiler
Different phases of a compiler
Sumit Sinha
 
9 subprograms
9 subprograms9 subprograms
9 subprograms
jigeno
 

Tendances (20)

C#3.0 & Vb 9.0 New Features
C#3.0 & Vb 9.0 New FeaturesC#3.0 & Vb 9.0 New Features
C#3.0 & Vb 9.0 New Features
 
Compiler design important questions
Compiler design   important questionsCompiler design   important questions
Compiler design important questions
 
FUNCTION CPU
FUNCTION CPUFUNCTION CPU
FUNCTION CPU
 
08 subprograms
08 subprograms08 subprograms
08 subprograms
 
Csci360 08-subprograms
Csci360 08-subprogramsCsci360 08-subprograms
Csci360 08-subprograms
 
Chapter 9 & chapter 10 solutions
Chapter 9 & chapter 10 solutionsChapter 9 & chapter 10 solutions
Chapter 9 & chapter 10 solutions
 
A brief introduction to C Language
A brief introduction to C LanguageA brief introduction to C Language
A brief introduction to C Language
 
9 subprograms
9 subprograms9 subprograms
9 subprograms
 
Compiler Design
Compiler DesignCompiler Design
Compiler Design
 
C for Engineers
C for EngineersC for Engineers
C for Engineers
 
Different phases of a compiler
Different phases of a compilerDifferent phases of a compiler
Different phases of a compiler
 
C programming interview questions
C programming interview questionsC programming interview questions
C programming interview questions
 
Unit 5 cspc
Unit 5 cspcUnit 5 cspc
Unit 5 cspc
 
New c sharp3_features_(linq)_part_ii
New c sharp3_features_(linq)_part_iiNew c sharp3_features_(linq)_part_ii
New c sharp3_features_(linq)_part_ii
 
9 subprograms
9 subprograms9 subprograms
9 subprograms
 
Introduction to Procedural Programming in C++
Introduction to Procedural Programming in C++Introduction to Procedural Programming in C++
Introduction to Procedural Programming in C++
 
C programming
C programming C programming
C programming
 
Ch2 C Fundamentals
Ch2 C FundamentalsCh2 C Fundamentals
Ch2 C Fundamentals
 
Unit 1 cd
Unit 1 cdUnit 1 cd
Unit 1 cd
 
9. control statement
9. control statement9. control statement
9. control statement
 

Similaire à New c sharp4_features_part_i

Presentation
PresentationPresentation
Presentation
bugway
 
Introduction to the c programming language (amazing and easy book for beginners)
Introduction to the c programming language (amazing and easy book for beginners)Introduction to the c programming language (amazing and easy book for beginners)
Introduction to the c programming language (amazing and easy book for beginners)
mujeeb memon
 
New c sharp3_features_(linq)_part_iv
New c sharp3_features_(linq)_part_ivNew c sharp3_features_(linq)_part_iv
New c sharp3_features_(linq)_part_iv
Nico Ludwig
 
Chapter-2 edited on Programming in Can refer this ppt
Chapter-2 edited on Programming in Can refer this pptChapter-2 edited on Programming in Can refer this ppt
Chapter-2 edited on Programming in Can refer this ppt
ANISHYAPIT
 

Similaire à New c sharp4_features_part_i (20)

Functions and modular programming.pptx
Functions and modular programming.pptxFunctions and modular programming.pptx
Functions and modular programming.pptx
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
Presentation
PresentationPresentation
Presentation
 
Rr
RrRr
Rr
 
Introduction to the c programming language (amazing and easy book for beginners)
Introduction to the c programming language (amazing and easy book for beginners)Introduction to the c programming language (amazing and easy book for beginners)
Introduction to the c programming language (amazing and easy book for beginners)
 
C pdf
C pdfC pdf
C pdf
 
C_plus_plus
C_plus_plusC_plus_plus
C_plus_plus
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Functions in c++, presentation, short and sweet presentation, and details of ...
Functions in c++, presentation, short and sweet presentation, and details of ...Functions in c++, presentation, short and sweet presentation, and details of ...
Functions in c++, presentation, short and sweet presentation, and details of ...
 
Learning the C Language
Learning the C LanguageLearning the C Language
Learning the C Language
 
C tour Unix
C tour UnixC tour Unix
C tour Unix
 
New c sharp3_features_(linq)_part_iv
New c sharp3_features_(linq)_part_ivNew c sharp3_features_(linq)_part_iv
New c sharp3_features_(linq)_part_iv
 
(3) cpp procedural programming
(3) cpp procedural programming(3) cpp procedural programming
(3) cpp procedural programming
 
Introduction to C#
Introduction to C#Introduction to C#
Introduction to C#
 
Chapter-2 edited on Programming in Can refer this ppt
Chapter-2 edited on Programming in Can refer this pptChapter-2 edited on Programming in Can refer this ppt
Chapter-2 edited on Programming in Can refer this ppt
 
Presentation c++
Presentation c++Presentation c++
Presentation c++
 
Lecture 1
Lecture 1Lecture 1
Lecture 1
 
Unit-2.pptx
Unit-2.pptxUnit-2.pptx
Unit-2.pptx
 
424769021-1-First-C-Program-1-ppt (1).ppt
424769021-1-First-C-Program-1-ppt (1).ppt424769021-1-First-C-Program-1-ppt (1).ppt
424769021-1-First-C-Program-1-ppt (1).ppt
 
venkatesh.pptx
venkatesh.pptxvenkatesh.pptx
venkatesh.pptx
 

Plus de Nico Ludwig

Plus de Nico Ludwig (20)

Grundkurs fuer excel_part_v
Grundkurs fuer excel_part_vGrundkurs fuer excel_part_v
Grundkurs fuer excel_part_v
 
Grundkurs fuer excel_part_iv
Grundkurs fuer excel_part_ivGrundkurs fuer excel_part_iv
Grundkurs fuer excel_part_iv
 
Grundkurs fuer excel_part_iii
Grundkurs fuer excel_part_iiiGrundkurs fuer excel_part_iii
Grundkurs fuer excel_part_iii
 
Grundkurs fuer excel_part_ii
Grundkurs fuer excel_part_iiGrundkurs fuer excel_part_ii
Grundkurs fuer excel_part_ii
 
Grundkurs fuer excel_part_i
Grundkurs fuer excel_part_iGrundkurs fuer excel_part_i
Grundkurs fuer excel_part_i
 
(2) gui drawing
(2) gui drawing(2) gui drawing
(2) gui drawing
 
(2) gui drawing
(2) gui drawing(2) gui drawing
(2) gui drawing
 
(1) gui history_of_interactivity
(1) gui history_of_interactivity(1) gui history_of_interactivity
(1) gui history_of_interactivity
 
(1) gui history_of_interactivity
(1) gui history_of_interactivity(1) gui history_of_interactivity
(1) gui history_of_interactivity
 
New c sharp4_features_part_vi
New c sharp4_features_part_viNew c sharp4_features_part_vi
New c sharp4_features_part_vi
 
New c sharp4_features_part_v
New c sharp4_features_part_vNew c sharp4_features_part_v
New c sharp4_features_part_v
 
New c sharp4_features_part_iv
New c sharp4_features_part_ivNew c sharp4_features_part_iv
New c sharp4_features_part_iv
 
New c sharp4_features_part_iii
New c sharp4_features_part_iiiNew c sharp4_features_part_iii
New c sharp4_features_part_iii
 
New c sharp4_features_part_ii
New c sharp4_features_part_iiNew c sharp4_features_part_ii
New c sharp4_features_part_ii
 
New c sharp3_features_(linq)_part_v
New c sharp3_features_(linq)_part_vNew c sharp3_features_(linq)_part_v
New c sharp3_features_(linq)_part_v
 
New c sharp3_features_(linq)_part_iv
New c sharp3_features_(linq)_part_ivNew c sharp3_features_(linq)_part_iv
New c sharp3_features_(linq)_part_iv
 
New c sharp3_features_(linq)_part_iii
New c sharp3_features_(linq)_part_iiiNew c sharp3_features_(linq)_part_iii
New c sharp3_features_(linq)_part_iii
 
New c sharp3_features_(linq)_part_i
New c sharp3_features_(linq)_part_iNew c sharp3_features_(linq)_part_i
New c sharp3_features_(linq)_part_i
 
New c sharp3_features_(linq)_part_i
New c sharp3_features_(linq)_part_iNew c sharp3_features_(linq)_part_i
New c sharp3_features_(linq)_part_i
 
Review of c_sharp2_features_part_iii
Review of c_sharp2_features_part_iiiReview of c_sharp2_features_part_iii
Review of c_sharp2_features_part_iii
 

Dernier

Dernier (20)

Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 

New c sharp4_features_part_i

  • 1. 1 Nico Ludwig (@ersatzteilchen) New C#4 Features – Part I
  • 2. 2 TOC ● New C#4 Features – Part I – Focus of C#4 Features – Simplifications in Syntax – Simplifications for Working with COM – Improvements in Code Generation ● Sources: – Jon Skeet, CSharp in Depth
  • 3. 3 Focus of C#4 ● Interoperability (basically not new CLR 4 features): – Enhancements for COM interoperability and PIA. – Dynamic typing and the Dynamic Language Runtime (DLR). ● VB and C# co/evolution (already in the CLR 1 and 2, now enabled in C#4): – Optional parameters, named arguments. – Configurable generic co- and contravariance for parameter and return types. ● Performance (new features in the CLR 4): – New threading model (esp. addressing thread pools and the gc). – Parallel extensions (Task Parallel Library (TPL), the types Task and Parallel, PLINQ). ● Code Quality: – Code Contracts ● Dynamic typing enables easy usage of COM types (e.g. Microsoft Office automation) and dynamic/scripting languages (IronRuby, IronPython). ● The CLR didn’t need to change in order to enable the DLR. ● PLINQ is implemented as a set of extension methods on ParallelQuery/<T>.
  • 4. 4 Named Arguments ● Positional and named arguments can be used as alternatives or in combination. ● It can enhance readability. ● (Good if certain parameters often change their position in declarations.) ● The names of formal parameters are now part of a type's public interface in C#. – .Net/CLR supported named arguments from the start. // Positional argument passing in C#1/C#2/C#3: anInstance.AMethod(42, 21); // New in C#4: named argument passing: anInstance.AMethod(foo: 42, bar: 21); /* or: */ anInstance.AMethod(bar: 21, foo: 42); // Let's assume that we'd like to call following method: public void AMethod(int foo, int bar) { /* pass */ } ● Named arguments are present in VB for a long time. Smalltalk and Objective-C use a combination of positional and named argument passing for all method calls. In CLOS there exist so-called "keywords" that work similar to named argument passing. ● Being part of the public interface means: ● Changing the name of a parameter could break calling code at compile time. We can circumvent this by avoiding the usage of named parameters or by avoiding to change the names of the parameters on public, or protected methods.
  • 5. 5 Named Arguments and optional Parameters in Action <NamedArgumentsAndOptionalParameters> Presents named arguments and optional parameters. ● These features will be shown in one example, because we will encounter them together in practice very often. ● Parameter: The variable being declared in the declaration of a function or method. ● Argument: The expression passed to a function or method.
  • 6. 6 Optional Parameters ● Make parameters optional by specification of a default value constant. – Can be used with almost all kinds of methods (incl. interfaces' methods). – Reduces the need for overloads. ● The CLR supported them from the start (via the OptionalAttribute). – Optional parameters are CLS compliant, but... ● The default values are compile time bound (like the resolution of overloads). – Can cause version problems similar to public constants. - Callers must recompile! – Prevent version problems: named arguments, overloads or value reinterpretation. // This method can be called this way: anInstance.DoSomething(42, 56); /* or this way: */ anInstance.DoSomething(42); // C#4's new syntax to declare a method having an optional parameter "bar": public void DoSomething(int foo, int bar = 0) { /* pass */ } ● Optional parameters were present in VB before it was a .Net language (often used as hack to simulate non-existing overloads in earlier versions of VB). ● Exactly as for constants the optional parameters' values are stored in the metadata of the assembly, thus we can only use primitive types. ● The default values need to be compile time constants: literals, incl. null (i.e. default(<ReferenceType>)) or any parameterless ctor of a value type (i.e. default(<ValueType>)) or const members or enum values; an implicit conversion to the parameter type must be existent (not a user defined conversion). For empty strings we have to use "" rather than string.Empty, because later is not a compile time constant but a static property. The restrictions are similar to custom attribute values. ● If we run the code analysis (CA) against code using optional parameters we'll get the warning CA1026 "Default parameters should not be used". Overloads are considered the better feature, because languages w/o optional parameter support need to pass all parameters. - The CA says: better avoid it (after the Framework Design Guidelines 5.1.1). ● The usage of optional parameters in internal and private methods is ok. ● To be frank there is one important advantage: optional parameters are itself a good documentation. ● Optional parameters seem to be similar to default arguments in C++. But they're not. In C++ default arguments don't need to be compile time constants. But in C++ we also have to recompile all callers of a function/method, if a default argument is a compile time constant and has been modified. Mind that in C++ we _have to recompile_ to do this, because the modification has then been done in an h-file (due to separated compilation); and whenever a h-file has changed _each_ includer must recompile. - Such a dependency isn't existing in C#, but recompilation against modified APIs comes into play when any public compile time constant has been changed. ● Optional parameters carry the "defaultvalue" attribute in COM.
  • 7. 7 Another practical Example: Value Interpretation <NamedArgumentsAndOptionalParameters> Solving versioning problems with value interpretation.
  • 8. 8 CLS Site of Named Arguments and Optional Parameters ● Default values of methods with optional parameters are stored on the caller site. – We can inspect the caller site (e.g. with Reflector) to see the default values (in IL code). – If the default value was modified, all callers need to recompile to get the new value. – If the callers don't recompile they will continue to use the previous default parameter. – Adding new optional parameters to public/protected methods will break at run time, if callers don't recompile! – => In effect methods can go silently incompatible! This is the versioning problem. – A ctor having only optional parameters is not accepted as parameterless ctor (dctor)! – (Method overloads are more robust than optional parameters.) ● The names of named arguments are stored on the caller site. – If a parameter's name was modified, formerly compiled callers will continue to work. – If a caller then tries to recompile, it needs to rename the named arguments respectively. – => Renamed parameters are only a breaking change on compile time afterwards. ● Method calls to methods with optional arguments can't be done in expression trees, if no arguments are passed. ● The break at run time does only happen, if a method of a referenced assembly was modified. Modifications in the same assembly can go really silently incompatible by using wrong or "shifted" default values. ● The versioning problem mentioned before is not existing when using overloads instead of optional parameters. Optional parameters couple the caller tighter than overloads. ● In C++ a ctor only having parameters with default arguments is automatically also a dctor. ● To make the versioning problem visible we can force developers to recompile their code, e.g. if we make the interface deliberately incompatible.
  • 9. 9 Summary: Named Arguments and Optional Parameters ● Enable features in C# that were already present in the CLR. ● Its combination is useful. – Esp. to reduce the noisiness of APIs like COM automation (more to come later). ● Can be used to with almost any kind of method (also ctors and indexers). – Can not be used to implement/call operator methods. ● Influence resolving of method overloads. – Named arguments may reduce the count of candidates on resolving. – Optional parameters may increase the count of candidates on resolving. ● These features were introduced into C# to improve the support of COM. ● Usefulness of the combination of named arguments and optional parameters: ● Named arguments and optional parameters can save 15 overloads of a four-parameter method! ● There exist MS Office APIs with up to 16 parameters! - We don't need to pass ten Type.Missing arguments and to fill the other six arguments with meaningful arguments, instead we just exploit the combination of named argument passing and optional parameters. ● C#'s indexers aren't operators. They aren't static methods and they can be defined with another arity. ● (In C++ the subscript operator can only be binary. However the function call operator can have any arity and can, as the only operator in C++, have default arguments.) ● Indexers can have default arguments, but it makes only sense having indexers with more than one parameter, because we can't directly call an indexer w/o specifying at least one argument in C#. ● Named arguments reduce the count of candidates, because only overloads having parameters with exactly the written names will be considered. ● Optional arguments increase the count of candidates, because some methods could have more parameters than the number of passed arguments. ● Named arguments and optional parameters are similar to positional and named parameters in .Net custom attributes.
  • 10. 10 COM Interop Improvements in Action <EvolutionOfComInteropImprovements> This example presents some Microsoft specific simplifications for COM interoperability. "COM is not dead, it is done!" Don Box, Nov. 2003
  • 11. 11 Summary: Simplifications for Working with COM ● I.e. simplifications for generated code of interop assemblies. ● COM does not support method overloads, so many parameters (and arguments) are required. – Optional parameters and named arguments come in handy... – ... in fact they have been introduced into C# only to support better COM interop. ● Almost all parameters in COM interfaces are ref parameters. – Values (e.g. literals) can be directly passed as arguments to ref parameters. ● One more simplification: Named indexers can be called easily. ● No-PIA deployment: PIA code can now be linked in instead of only referenced. – Only the used types will be linked/embedded into our resulting assembly. – Self contained assemblies have a smaller "footprint" and reduce version problems. ● Mind that the simplifications shown in this section are highly Microsoft dependent. ● E.g. there exist MS Office COM APIs with up to 16 parameters! ● The usage of ref parameters in COM is due to performance gains (often seen with VARIANTs that must be passed as plain objects). Typically the arguments aren't modified within these COM methods. ● Named indexers can only be called in C#, but we can't define new ones. (These so called "indexed properties" are known in the CLR and applicable in VB since .Net1. The unnamed indexed property (i.e. the "indexer") present in C# is called "default property/member".) ● Named indexers in generated interop code, that only have optional arguments, can also be called from C#. ● No-PIA deployment bases on .Net 4's new feature "type equivalence". It allows the run time to consider certain types as being interchangeable even if they are defined in different assemblies, so it enhances interoperability. The idea of PIA was that only one assembly contains all the types, this was relaxed with type equivalence. Every linked-in copy of the type gets a TypeIdentifier attribute that declares equivalent types with a common identifier (not for types with behavior, only interfaces, delegates, enums and PODs). ● No-PIA deployed types will enable dynamic coding that simplifies working with COM (esp. with IDispatch and VARIANTs) even further. This will be discussed in a later lecture...
  • 12. 12 Improvements in Code Generation ● Some less prominent changes for thread-safety made their way into C#4. ● The lock statement's implementation got more robust. – The generated code uses monitors in a thread-safe and exception-safe fashion. ● Field-like events' implementation got more robust. – The this reference or the type of the surrounding type won't be locked any longer. ● Instead on add/remove an atomic Interlocked.CompareExchange<T>()-call is used. – The +=/-= operators will always be performed on the event field. ● Also within the declaring class. Before C#3 it was performed on the backing field directly! ● This was done to exploit the gained thread-safety as explained above (read: atomicity). ● (On other operations (assignment/call), the backing field will still be used directly.)