SlideShare a Scribd company logo
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!

More Related Content

PDF
Embedded C - Optimization techniques
PDF
FregeDay: Roadmap for resolving differences between Haskell and Frege (Ingo W...
PPTX
Functional Programming in JavaScript & ESNext
PDF
FregeDay: Design and Implementation of the language (Ingo Wechsung)
PPTX
Introduction to C programming
PPTX
PPTX
C#unit4
PPTX
10 implementing subprograms
Embedded C - Optimization techniques
FregeDay: Roadmap for resolving differences between Haskell and Frege (Ingo W...
Functional Programming in JavaScript & ESNext
FregeDay: Design and Implementation of the language (Ingo Wechsung)
Introduction to C programming
C#unit4
10 implementing subprograms

What's hot (20)

PPT
C#3.0 & Vb 9.0 New Features
DOCX
Compiler design important questions
PPTX
FUNCTION CPU
PDF
08 subprograms
PPT
Csci360 08-subprograms
DOCX
Chapter 9 & chapter 10 solutions
PPTX
A brief introduction to C Language
PPTX
9 subprograms
PPTX
Compiler Design
PPTX
C for Engineers
PDF
Different phases of a compiler
PPTX
C programming interview questions
PPT
Unit 5 cspc
PDF
New c sharp3_features_(linq)_part_ii
PDF
9 subprograms
PPT
Introduction to Procedural Programming in C++
PPTX
C programming
PPTX
Ch2 C Fundamentals
KEY
Unit 1 cd
PPTX
9. control statement
C#3.0 & Vb 9.0 New Features
Compiler design important questions
FUNCTION CPU
08 subprograms
Csci360 08-subprograms
Chapter 9 & chapter 10 solutions
A brief introduction to C Language
9 subprograms
Compiler Design
C for Engineers
Different phases of a compiler
C programming interview questions
Unit 5 cspc
New c sharp3_features_(linq)_part_ii
9 subprograms
Introduction to Procedural Programming in C++
C programming
Ch2 C Fundamentals
Unit 1 cd
9. control statement
Ad

Similar to New c sharp4_features_part_i (20)

PPTX
Functions and modular programming.pptx
PPTX
POLITEKNIK MALAYSIA
PPTX
Function Overloading Call by value and call by reference
PDF
Presentation
PDF
Introduction to the c programming language (amazing and easy book for beginners)
PDF
Rr
PDF
C pdf
PPTX
C_plus_plus
PPTX
FUNCTIONengineeringtechnologyslidesh.pptx
PPTX
FUNCTION.pptxfkrdutytrtttrrtttttttttttttt
PPT
Functions in C++
PPTX
Functions in c++, presentation, short and sweet presentation, and details of ...
 
PPTX
c & c++ logic building concepts practice.pptx
PDF
Learning the C Language
PPTX
CSC 204 PASSES IN COMPILER CONSTURCTION.pptx
PDF
C tour Unix
ODP
New c sharp3_features_(linq)_part_iv
PDF
(3) cpp procedural programming
PPTX
Introduction to C#
PDF
SPCC_Sem6_Chapter 6_Code Optimization part
Functions and modular programming.pptx
POLITEKNIK MALAYSIA
Function Overloading Call by value and call by reference
Presentation
Introduction to the c programming language (amazing and easy book for beginners)
Rr
C pdf
C_plus_plus
FUNCTIONengineeringtechnologyslidesh.pptx
FUNCTION.pptxfkrdutytrtttrrtttttttttttttt
Functions in C++
Functions in c++, presentation, short and sweet presentation, and details of ...
 
c & c++ logic building concepts practice.pptx
Learning the C Language
CSC 204 PASSES IN COMPILER CONSTURCTION.pptx
C tour Unix
New c sharp3_features_(linq)_part_iv
(3) cpp procedural programming
Introduction to C#
SPCC_Sem6_Chapter 6_Code Optimization part
Ad

More from Nico Ludwig (20)

PPTX
Grundkurs fuer excel_part_v
PPTX
Grundkurs fuer excel_part_iv
PPTX
Grundkurs fuer excel_part_iii
PPTX
Grundkurs fuer excel_part_ii
PPTX
Grundkurs fuer excel_part_i
PDF
(2) gui drawing
ODP
(2) gui drawing
PDF
(1) gui history_of_interactivity
ODP
(1) gui history_of_interactivity
PDF
New c sharp4_features_part_vi
PDF
New c sharp4_features_part_v
PDF
New c sharp4_features_part_iv
ODP
New c sharp4_features_part_iii
PDF
New c sharp4_features_part_ii
PDF
New c sharp3_features_(linq)_part_v
PDF
New c sharp3_features_(linq)_part_iv
PDF
New c sharp3_features_(linq)_part_iii
PDF
New c sharp3_features_(linq)_part_i
ODP
New c sharp3_features_(linq)_part_i
PDF
Review of c_sharp2_features_part_iii
Grundkurs fuer excel_part_v
Grundkurs fuer excel_part_iv
Grundkurs fuer excel_part_iii
Grundkurs fuer excel_part_ii
Grundkurs fuer excel_part_i
(2) gui drawing
(2) gui drawing
(1) gui history_of_interactivity
(1) gui history_of_interactivity
New c sharp4_features_part_vi
New c sharp4_features_part_v
New c sharp4_features_part_iv
New c sharp4_features_part_iii
New c sharp4_features_part_ii
New c sharp3_features_(linq)_part_v
New c sharp3_features_(linq)_part_iv
New c sharp3_features_(linq)_part_iii
New c sharp3_features_(linq)_part_i
New c sharp3_features_(linq)_part_i
Review of c_sharp2_features_part_iii

Recently uploaded (20)

PDF
Web App vs Mobile App What Should You Build First.pdf
PDF
STKI Israel Market Study 2025 version august
PDF
August Patch Tuesday
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PDF
Microsoft Solutions Partner Drive Digital Transformation with D365.pdf
PDF
Hybrid model detection and classification of lung cancer
PDF
Developing a website for English-speaking practice to English as a foreign la...
PDF
WOOl fibre morphology and structure.pdf for textiles
PDF
2021 HotChips TSMC Packaging Technologies for Chiplets and 3D_0819 publish_pu...
PPTX
Group 1 Presentation -Planning and Decision Making .pptx
PPTX
observCloud-Native Containerability and monitoring.pptx
PDF
NewMind AI Weekly Chronicles – August ’25 Week III
PDF
Zenith AI: Advanced Artificial Intelligence
PDF
A novel scalable deep ensemble learning framework for big data classification...
PDF
Architecture types and enterprise applications.pdf
PPTX
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
PDF
Univ-Connecticut-ChatGPT-Presentaion.pdf
PDF
From MVP to Full-Scale Product A Startup’s Software Journey.pdf
PDF
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
PDF
Assigned Numbers - 2025 - Bluetooth® Document
Web App vs Mobile App What Should You Build First.pdf
STKI Israel Market Study 2025 version august
August Patch Tuesday
NewMind AI Weekly Chronicles - August'25-Week II
Microsoft Solutions Partner Drive Digital Transformation with D365.pdf
Hybrid model detection and classification of lung cancer
Developing a website for English-speaking practice to English as a foreign la...
WOOl fibre morphology and structure.pdf for textiles
2021 HotChips TSMC Packaging Technologies for Chiplets and 3D_0819 publish_pu...
Group 1 Presentation -Planning and Decision Making .pptx
observCloud-Native Containerability and monitoring.pptx
NewMind AI Weekly Chronicles – August ’25 Week III
Zenith AI: Advanced Artificial Intelligence
A novel scalable deep ensemble learning framework for big data classification...
Architecture types and enterprise applications.pdf
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
Univ-Connecticut-ChatGPT-Presentaion.pdf
From MVP to Full-Scale Product A Startup’s Software Journey.pdf
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
Assigned Numbers - 2025 - Bluetooth® Document

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.)