<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Pragmateek</title>
	<atom:link href="http://pragmateek.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://pragmateek.com</link>
	<description>A geek on his way to IT pragmatism</description>
	<lastBuildDate>Mon, 21 Nov 2022 00:07:08 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=5.2.24</generator>
	<item>
		<title>Why C# structs do no support inheritance</title>
		<link>http://pragmateek.com/why-c-structs-do-no-support-inheritance/</link>
				<comments>http://pragmateek.com/why-c-structs-do-no-support-inheritance/#respond</comments>
				<pubDate>Mon, 21 Nov 2022 00:05:06 +0000</pubDate>
		<dc:creator><![CDATA[pragmateek]]></dc:creator>
				<category><![CDATA[.Net Development]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[inheritance]]></category>
		<category><![CDATA[object-oriented-programming]]></category>
		<category><![CDATA[struct]]></category>

		<guid isPermaLink="false">http://pragmateek.com/?p=3698</guid>
				<description><![CDATA[Introduction A common question asked by C# developers is why structs (the representation of .NET value types in the C# language) do not support inheritance whereas classes (.NET reference types) do? I see three reasons: Design choice Conflict with array &#8230; <a href="http://pragmateek.com/why-c-structs-do-no-support-inheritance/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
								<content:encoded><![CDATA[



<h2>Introduction</h2>



<p>A common question asked by C# developers is why <strong>structs</strong> (the representation of <strong>.NET value types</strong> in the <strong>C# language</strong>) do not support inheritance whereas <strong>classes</strong> (<strong>.NET reference types</strong>) do?</p>



<p>I see three reasons:</p>



<ul><li>Design choice</li><li>Conflict with array covariance</li><li>Memory management</li></ul>



<p>As <strong>C#</strong> is the main language of the <strong>.NET platform</strong> I&#8217;ll use the term <strong>struct</strong> in this article instead of <strong>value type</strong>.</p>



<span id="more-3698"></span>



<h2>#1 Design</h2>



<p>The first reason is that structs have been designed to be <strong>lightweight</strong>, and one of their primary uses is to represent simple <strong>data structures</strong> like points or colours which are basically a set of <strong>primitive data</strong>.</p>



<p>Preventing inheritance has not only conceptual implications by guiding the usage, but also technical as no inheritance means no need for a <strong>vtable</strong> to store the pointers to <strong>virtual methods</strong> that may be overridden further down the types hierarchy.</p>



<p>In the same way instances of structs do not have an <strong>object header</strong> which stores <strong>metadata</strong> like type information along with a <strong>sync-block</strong> used to take a lock on the object in <strong>multi-threaded</strong> programs.</p>



<p>So in memory structs instances are merely a sequence of fields storage.</p>



<p>Of course if any operation, like calling a <strong>virtual methods</strong> inherited from <code>System.Object</code> like <code>ToString</code>, imply the usage of these &#8220;missing&#8221; parts a <strong>reference-type box</strong> wrapping a copy of the instance is used instead.</p>



<h2>#2 Array covariance</h2>



<p>The second reason is a technical arbitrage: you cannot have both struct inheritance and <strong>array covariance</strong>.</p>



<p>In a type-system context, <strong>covariance</strong> is the fact that if a type inherits from another, this relation exists also between types derived from these types.<br>As an example if <code>B</code> inherits from <code>A</code>, then references to <code>B</code> are also considered references to <code>A</code>, and can be substituted by them, which allows dynamic polymorphism.</p>



<p>In C# the vectorization of <strong>references</strong> is also covariant: if <code>B</code> inherits from <code>A</code> and can be substituted to <code>A</code>, then an array <code>B[]</code> of references to <code>B</code> instances  can be substituted to an array <code>A[]</code> of references to <code>A</code> instances.<br>This is possible because all references have the same memory representation.</p>



<p>Here is an illustration:</p>


<pre class="brush: csharp; title: ; notranslate">
using static System.Console;
using System.Linq;

long F(A[] a) =&gt; a.Sum(x =&gt; x.n);

A[] a = { new B { n = 1 }, new B { n = 2 }, new B { n = 3 } };

WriteLine(F(a));

class A
{
	public int n;
}

class B : A
{
}
</pre>


<p>Compilation and run:</p>



<pre class="wp-block-preformatted">&gt;csc Test.cs
 Compilateur Microsoft (R) Visual C# version 4.4.0-3.22518.13 (7856a68c)
 Copyright (C) Microsoft Corporation. Tous droits réservés.
&gt;Test.exe
 6</pre>



<h3>What could go wrong?</h3>



<p>So what could go wrong if we also had structs inheritance?<br>We could end with arrays of instances of derived struct <code>B</code> used where an array of instances of the base struct <code>A</code> is expected, and as more often than not the instances of <code>B</code> will occupy more memory than instances of <code>A</code>, as more fields are added, the memory address calculation to reach the ith element of the array will be wrong.</p>



<p>Here is an illustration in C++:</p>


<pre class="brush: cpp; title: ; notranslate">
#include &lt;iostream&gt;

struct A {
	int na;
};

struct B : A {
	int nb;
};

void f(A as[]) {
	std::cout &lt;&lt; as[0].na &lt;&lt; &quot;|&quot; &lt;&lt; as[1].na &lt;&lt; &quot;|&quot; &lt;&lt; as[2].na &lt;&lt; std::endl;
}

int main() {
	B bs[] = { B{ A{1}, 2}, B{ A{3}, 4}, B{ A{5}, 6}};

	f(bs);

	return 0;
}
</pre>


<p><span style="text-decoration: underline;">Note</span>: in C++ <code>struct</code>s have not at all the same semantics as in C#: it only impacts the default visibility of members (<code>public</code>) and the default inheritance type (<code>public</code>).</p>



<p>Compilation:</p>



<pre class="wp-block-preformatted">>cl /std:c++latest /EHsc test.cpp
   Microsoft (R) C/C++ Optimizing Compiler Version 19.34.31933 for x64
   Copyright (C) Microsoft Corporation.  All rights reserved. 
 /std:c++latest is provided as a preview of language features from the latest C++
 working draft, and we're eager to hear about bugs and suggestions for improvements.
 However, note that these features are provided as-is without support, and subject
 to changes or removal as the working draft evolves. See
 https://go.microsoft.com/fwlink/?linkid=2045807 for details.
 test.cpp
 Microsoft (R) Incremental Linker Version 14.34.31933.0
 Copyright (C) Microsoft Corporation.  All rights reserved.
 /out:test.exe
 test.obj</pre>



<p>Run:</p>



<pre class="wp-block-preformatted">>test.exe
1|2|3</pre>



<p>So we get <code>1|2|3</code> instead of <code>1|3|5</code>, so what happened?<br>The issue is that the memory representation of instances of <code>A</code> and <code>B</code> are not the same: <code>B</code> ones are twice as big as <code>A</code> ones, so the pointer arithmetic to get to the ith instance in the array is not the same with an array of <code>A</code> or <code>B</code>.</p>



<p>Here is a representation of the array <code>bs</code>:</p>



<pre class="wp-block-preformatted">+----------+---------+----------+
|     0    |    1    |    2     |
|+----+----+----+----+----+----+|
||    B    |    B    |    B    ||
|+----+----+----+----+----+----+|
||  1 |  2 |  3 |  4 |  5 |  6 ||
|+----+----+----+----+----+----+|
+-------------------------------+</pre>



<p>It contains 3 instances of <code>B</code> stored side by side at indices 0, 1, and 2.<br>But the function <code>f</code> interprets it as:</p>



<pre class="wp-block-preformatted">+----------+---------+----------+
|   0 |  1 |  2 |  3 |  4 |  5  |
|+----+----+----+----+----+----+|
||  A |  A |  A |  A |  A |  A ||
|+----+----+----+----+----+----+|
||  1 |  2 |  3 |  4 |  5 |  6 ||
|+----+----+----+----+----+----+|
+-------------------------------+</pre>



<p>And mechanically goes from one item in the array to the next by incrementing the address by the size of an instance of <code>A</code> and not the size of an instance of <code>B</code>. </p>



<p>The solution is to make a copy of the <code>bs</code> array to another with the expected memory layout:</p>


<pre class="brush: cpp; title: ; notranslate">
#include &lt;iostream&gt;
#include &lt;algorithm&gt;

struct A {
	int na;
};

struct B : A {
	int nb;
};

void f(A as[]) {
	std::cout &lt;&lt; as[0].na &lt;&lt; &quot;|&quot; &lt;&lt; as[1].na &lt;&lt; &quot;|&quot; &lt;&lt; as[2].na &lt;&lt; std::endl;
}

int main() {
	B bs[] = { B{ A{1}, 2}, B{ A{3}, 4}, B{ A{5}, 6}};
	
	A as[3];
	std::copy(std::begin(bs), std::end(bs), std::begin(as));

	f(as);

	return 0;
}
</pre>


<p>During the copy process, each instance of <code>B</code> is mapped (<strong>sliced</strong>, see #3) to an instance of <code>A</code>, and we get this array:</p>



<pre class="wp-block-preformatted">+-----+----+----++
|   0 |  1 |  2  |
|+----+----+----+|
||  A |  A |  A ||
|+----+----+----+|
||  1 |  3 |  5 ||
|+----+----+----+|
+----------------+</pre>



<p>Same compilation.<br>Run:</p>



<pre class="wp-block-preformatted">>test.exe
1|3|5 </pre>



<p>As expected we get the values of the <code>na</code> fields of the <code>B</code> instances which have been copied to the new <code>A</code> instances.</p>



<h3>But wait!</h3>



<p>But we have inheritance for <code>struct</code>s as they inherit from <code>System.ValueType</code> which itself inherits from <code>System.Object</code> as all .NET types.</p>



<p>So we could trick this restriction further up the inheritance hierarchy if we can&#8217;t further down:</p>


<pre class="brush: csharp; title: ; notranslate">
A[] a = { new A() };

object[] o = a;

struct A
{
}
</pre>


<p>Compilation:</p>



<pre class="wp-block-preformatted">>csc Test.cs
 Compilateur Microsoft (R) Visual C# version 4.4.0-3.22518.13 (7856a68c)
 Copyright (C) Microsoft Corporation. Tous droits réservés.
 Test.cs(3,14): error CS0029: Cannot implicitly convert type 'A[]' to 'object[]'</pre>



<p>So all is safe: when we have <strong>inheritance</strong> we cannot have <strong>covariance</strong>.<br>The reason is that the memory representation of items in <code>object[]</code>, <strong>references</strong> pointing to objects themselves, has nothing to do with those of instances of <code>A</code> directly stored side by side into the array.</p>



<p>As in C++, the solution is to copy the array to another array with the correct memory layout:</p>


<pre class="brush: csharp; title: ; notranslate">
A[] a = { new A() };

object[] o = new object[a.Length];

System.Array.Copy(a, o, a.Length);
</pre>


<p>During the copy from the array <code>a</code> to the array <code>o</code>, the instances of <code>A</code> are <strong>boxed</strong> and the references to these boxes are stored in the array <code>o</code>, so as statically declared <code>o</code> is an array of references to objects.</p>



<p>So in conclusion:</p>



<ul><li>if we don&#8217;t have covariance inheritance is safe because a <code>B[]</code> could not be substituted where an <code>A[]</code> is expected, this is <strong>C++</strong> choice,</li><li>if we don&#8217;t have inheritance covariance is safe because <code>A[]</code> cannot reference a <code>B[]</code> as not <code>B</code> can exist, this is <strong>C#</strong> choice.</li></ul>



<h2>#3 Memory management</h2>



<p>And finally <strong>memory management</strong>, a debatable reason, as we&#8217;ll see, which is often invoked: what would happen if an instance of a <strong>derived struct</strong> is copied to a variable hosting an instance of a <strong>base struct</strong>?</p>



<p>Here is an illustration:</p>


<pre class="brush: plain; title: ; notranslate">
struct A
{
    public int NA;
}

struct B : A
{
    public int NB;
}

A a = new B();
</pre>


<p>Indeed with a naive implementation that would copy the whole <code>B</code> instance into <code>a</code> memory, you might end up breaking the <strong>memory safety</strong>, corrupting neighbouring memory as <code>B</code> instances are larger than <code>A</code> instances.</p>



<p>But there exists a well-known solution, implemented by <strong>C++</strong>: <strong>slicing</strong>.<br>The idea is to only copy the part of the <code>B</code> instance which is inherited from <code>A</code> (and makes it an <code>A</code>).<br>Here is an illustration in C++, along with a demonstration of what happens if we dodge it:</p>


<pre class="brush: cpp; title: ; notranslate">
#include &lt;iostream&gt;

struct A {
	int64_t na;
};

struct B : A {
	int64_t nb;
};

int main() {
	B b { A{1}, 1 };
	A a1 = {2};
	A a2 = {3};
	
	a1 = b;
	std::cout &lt;&lt; &quot;With slicing: &quot; &lt;&lt; a1.na &lt;&lt; &quot;|&quot; &lt;&lt; a2.na &lt;&lt; std::endl;
	
	*(B*)&amp;amp;a1 = b;
	std::cout &lt;&lt; &quot;Without slicing: &quot; &lt;&lt; a1.na &lt;&lt; &quot;|&quot; &lt;&lt; a2.na &lt;&lt; std::endl;

	return 0;
}
</pre>


<p>The first assignment <code>a1 = b</code> uses the default C++ behaviour, leveraging <strong>slicing</strong>.</p>



<p>The second one <code>*(B*)&amp;a1 = b</code> bypasses slicing by artificially creating a <code>B</code> <strong>left-value</strong> to reproduce what would happen without slicing:</p>



<ul><li><code>&amp;a1</code> gets an <code>A*</code> <strong>pointer</strong> to <code>a1</code>,</li><li><code>(B*)</code> casts it to a <code>B*</code> pointer, breaking <strong>type-safety</strong> by the way,</li><li>and finally <code>*</code> dereferences it to present a <code>B</code> instance.</li></ul>



<p><span style="text-decoration: underline;">Note</span>: I&#8217;ve used <code>int64_t</code> as the code was compiled and run on a <strong>64-bit</strong> machine and for performance reasons the compiler aligns the structs&#8217; instances memory to 8 bytes <strong>memory boundaries</strong>, hence preventing the demonstration of the issue as the corrupted memory is not used anyway.</p>



<p>Compilation:</p>



<pre class="wp-block-preformatted">&gt;cl /std:c++latest /EHsc test.cpp
   Microsoft (R) C/C++ Optimizing Compiler Version 19.34.31933 for x64
   Copyright (C) Microsoft Corporation.  All rights reserved. 
 /std:c++latest is provided as a preview of language features from the latest C++
 working draft, and we're eager to hear about bugs and suggestions for improvements.
 However, note that these features are provided as-is without support, and subject
 to changes or removal as the working draft evolves. See
 https://go.microsoft.com/fwlink/?linkid=2045807 for details.
 test.cpp
 test.cpp(19) : warning C4789: buffer 'a1' of size 8 bytes will be overrun; 16 bytes will be written starting at offset 0
 Microsoft (R) Incremental Linker Version 14.34.31933.0
 Copyright (C) Microsoft Corporation.  All rights reserved.
 /out:test.exe
 test.obj</pre>



<p>Note that the compiler has spotted the issue with the second assignment.</p>



<p>Run:</p>



<pre class="wp-block-preformatted">  &gt;test.exe
   With slicing: 1|3
   Without slicing: 1|1</pre>



<p>So the first assignment, with slicing, is perfectly memory-safe: only <code>a1</code> has been affected.<br>But the second assignment, without slicing, also affects <code>a2</code>, a sign that memory has been corrupted.</p>



<p>Let&#8217;s explain what happened in detail.<br>Here is a representation of the memory before the first assignment:</p>



<pre class="wp-block-preformatted">+--------+--------+--------+--------+
|        b        |   a1   |   a2   |
+--------+--------+--------+--------+
|   na   |   nb   |   na   |   na   |
+--------+--------+--------+--------+
|   1    |   1    |   2    |   3    |
+--------+--------+--------+----+---+</pre>



<p>The 3 instances memory slots are contiguous.<br>Then after the first assignment:</p>



<pre class="wp-block-preformatted">+--------+--------+--------+--------+
|        b        |   a1   |   a2   |
+--------+--------+--------+--------+
|   na   |   nb   |   na   |   na   |
+--------+--------+--------+--------+
|   1    |   1    |   1    |   3    |
+--------+--------+--------+----+---+</pre>



<p>Thanks to slicing only <code>b.na</code> has been copied to <code>a1</code>, only setting <code>a1.na</code>.</p>



<p>But without slicing, the entire <code>b</code> is copied to <code>a1</code> overflowing on <code>a2</code> which is stored right behind<br>So after the second assignment, we get:</p>



<pre class="wp-block-preformatted">+--------+--------+--------+--------+
|        b        |   a1   |   a2   |
+--------+--------+--------+--------+
|   na   |   nb   |   na   |   na   |
+--------+--------+--------+--------+
|   1    |   1    |   1    |   1    |
+--------+--------+--------+----+---+</pre>



<p>As expected not only <code>a1.n</code>  but also <code>a2.n</code> was set.</p>



<p>So while it is a real technical issue it has a well-known solution implemented by C++ for decades, but most C# programmers, myself included, are not fluent in C++, so it is largely unknown.  </p>



<p>But while slicing probably could have been implemented since the inception of .NET and C#, it would imply more complexity in the <strong>C# compiler</strong> and/or <strong>.NET CLR</strong>.</p>



<h2>Conclusion</h2>



<p>So we have presented 3 good reasons for .NET/C# not to support value-types/struct inheritance.</p>



<p>If you know about any other reasons please share.</p>
]]></content:encoded>
							<wfw:commentRss>http://pragmateek.com/why-c-structs-do-no-support-inheritance/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
							</item>
		<item>
		<title>Objects creation in C# vs C++</title>
		<link>http://pragmateek.com/objects-creation-in-cs-vs-cpp/</link>
				<comments>http://pragmateek.com/objects-creation-in-cs-vs-cpp/#comments</comments>
				<pubDate>Sat, 12 Nov 2022 19:45:03 +0000</pubDate>
		<dc:creator><![CDATA[pragmateek]]></dc:creator>
				<category><![CDATA[.Net Development]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[dotnet]]></category>
		<category><![CDATA[memory]]></category>

		<guid isPermaLink="false">http://pragmateek.com/?p=3662</guid>
				<description><![CDATA[Introduction Sometimes the way two languages implement a feature can significantly differ in surprising ways, and even the keywords can be misleading.This is the case of instantiation of C++ classes and C# structs a.k.a. .NET value types. In this article, &#8230; <a href="http://pragmateek.com/objects-creation-in-cs-vs-cpp/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
								<content:encoded><![CDATA[



<h2>Introduction</h2>



<p>Sometimes the way two languages implement a feature can significantly differ in surprising ways, and even the keywords can be misleading.<br>This is the case of instantiation of <strong>C++</strong> <strong>classes</strong> and <strong>C#</strong> <strong>structs</strong> a.k.a. <strong>.NET</strong> value types.</p>



<p>In this article, we will see the differences between the two languages in the way they handle the creation of objects: their memory allocation and their initialization.</p>



<span id="more-3662"></span>



<h2>.NET and C#</h2>



<p>First a quick introduction to the main difference between C++ and the pair .NET/C#.</p>



<p>With <strong>C++</strong> source code is directly compiled to <strong>machine binary code</strong> and run by the OS.</p>



<p><strong>.NET</strong> is an <strong>object-oriented</strong> (OO) managed platform with a <strong>runtime</strong>, the <strong>Common Language Runtime</strong> a.k.a. <strong>CLR</strong>, much like the <strong>Java Virtual Machine</strong> a.k.a. <strong>JVM</strong>, which is running its own binary code, a <strong>bytecode</strong> called the <strong>Common Intermediate Language</strong> a.k.a. <strong>CIL</strong> a.k.a <strong>MSIL</strong>, that it compiles to native code that is run by the OS.<br>The CLR is also responsible for <strong>managing the memory</strong> by allocating it, tracking it, and freeing it.</p>



<p>.NET supports many languages, <strong>C#</strong> being the main one, whose source code is compiled to this binary code which is stored to specific binary files called assemblies with the same typology and roles as native ones: <code>.exe</code> <strong>executables</strong> and <code>.dll</code> <strong>libraries</strong>.</p>



<p>Note that there is a version of C++ compiled to .NET CIL: <strong>C++/CLI</strong> whose you can see a concrete use-case in this other article: <a rel="noreferrer noopener" aria-label="Using C# from native C++ with the help of C++/CLI (opens in a new tab)" href="https://pragmateek.com/using-c-from-native-c-with-the-help-of-ccli-v2/" target="_blank">Using C# from native C++ with the help of C++/CLI</a>.</p>



<h2>Classes typology</h2>



<h3>C++</h3>



<p>In C++ there is only one type of <strong>class</strong>, the only difference between declaring them with the keyword <code>class</code> or <code>struct</code> is the default <strong>visibility</strong> of members: <strong>private</strong> for <code>class</code>, <strong>public</strong> for <code>struct</code>.</p>



<p>Moreover, in C++ the way an object&#8217;s memory is allocated does not depend on the object&#8217;s type.<br>Especially any class instance can be stored on the stack by simply declaring it, or the heap via the <code>new</code> operator.</p>



<h3>.NET and C#</h3>



<p>In .NET this is a different story, there is still a single concept of class (declared with the <code>.class</code> directive in CIL) but there are two distinct <strong>hierarchies</strong>:</p>



<ul><li><strong>Reference types</strong>: classes directly inheriting from <code>System.Object</code></li><li><strong>Value types</strong>: classes inheriting from <code>System.ValueType</code> (which itself inherits from <code>System.Object</code>)</li></ul>



<p>Their semantics differs:</p>



<ul><li>Reference types are intended to represent full-blown OO classes with most of the features you can expect from an OO platform (except multiple inheritance),</li><li>Value types are intended to represent data structures, a bit like <strong>C</strong> <code>struct</code>s, though they support many more OO features like methods and can be used polymorphically through interfaces,  but they have some limitations like no support for inheritance.</li></ul>



<p>Their memory is managed differently by the CLR:</p>



<ul><li>Reference types instances are always allocated on the <strong>heap</strong> and are accessed through <strong>typed references</strong> (themselves allocated &#8220;in place&#8221;),</li><li>Value types instances are allocated &#8220;in place&#8221; and hence can never be allocated by themselves on the heap but only as a part of another reference type instance (an array, an object).</li></ul>



<p>In this article, we only use value types as their instances can live both on the stack and the heap, so we&#8217;ll be able to reproduce the same scenarios as C++.</p>



<p>At the language level in <strong>C#</strong> we can define a reference type by introducing it with the <code>class</code> keyword, and a value type with the <code>struct</code> keyword, which is greatly misleading for C++ developers as in C++ the two keywords are technically almost synonymous.</p>



<h2>Objects initialization</h2>



<h3>C++</h3>



<p>C++ is quite permissive with regard to memory initialization so you can end up with objects containing &#8220;random&#8221; data left there by previous objects&#8217; allocations and bugs whose root cause is harder to find as the effects can appear far from the buggy code.<br>It&#8217;s not an issue by itself, just a design choice.</p>



<p>Here is an illustration:</p>


<pre class="brush: cpp; title: ; notranslate">
#include &lt;iostream&gt;

struct A {
	int N;	
};

struct B {
	int N;
	
	B() {
	}
};

void f() {
	std::cout &lt;&lt; &quot;Write data to the stack&quot; &lt;&lt; std::endl;
	
	A a;
	a.N = 123;
	
	B b;
	b.N = 456;
	
	std::cout &lt;&lt; &quot;a.N: &quot; &lt;&lt; a.N &lt;&lt; std::endl;
	std::cout &lt;&lt; &quot;b.N: &quot; &lt;&lt; b.N &lt;&lt; std::endl;
}

void g() {
	std::cout &lt;&lt; &quot;Without explicit constructor call&quot; &lt;&lt; std::endl;
	
	A a;
	B b;
	
	std::cout &lt;&lt; &quot;a.N: &quot; &lt;&lt; a.N &lt;&lt; std::endl;
	std::cout &lt;&lt; &quot;b.N: &quot; &lt;&lt; b.N &lt;&lt; std::endl;
}

void h() {
	std::cout &lt;&lt; &quot;With explicit constructor call&quot; &lt;&lt; std::endl;
	
	A a = A();
	B b = B();
	
	std::cout &lt;&lt; &quot;a.N: &quot; &lt;&lt; a.N &lt;&lt; std::endl;
	std::cout &lt;&lt; &quot;b.N: &quot; &lt;&lt; b.N &lt;&lt; std::endl;
}

int main() {
	f();
	g();
	h();

	return 0;
}
</pre>


<p>Compilation:</p>



<pre class="wp-block-preformatted">&gt;cl /EHsc test.cpp
 Microsoft (R) C/C++ Optimizing Compiler Version 19.34.31933 for x64
 Copyright (C) Microsoft Corporation.  All rights reserved.
 test.cpp
 test.cpp(28) : warning C4700: uninitialized local variable 'a' used
 Microsoft (R) Incremental Linker Version 14.34.31933.0
 Copyright (C) Microsoft Corporation.  All rights reserved.
 /out:test.exe
 test.obj</pre>



<p>Note that the compiler detects the potential issue and emits a warning. </p>



<p>Run:</p>



<pre class="wp-block-preformatted">&gt;test.exe
 Write data to the stack
 a.N: 123
 b.N: 456
 Without explicit constructor call
 a.N: 123
 b.N: 456
 With explicit constructor call
 a.N: 0
 b.N: 123</pre>



<p>So by default, the memory is not zeroed and you end up with objects filled up with the state of the previously allocated objects in the same place on the stack.</p>



<p>And you can see the different semantics of zero-initialization with an explicit call to the default constructor when it is explicitly defined or not.</p>



<h3>C#</h3>



<p>C# takes the opposite tack by forcing the developer to ensure the memory is fully initialized before using it, either by:</p>



<ul><li>Initializing all the fields after full object allocation</li><li>Calling a constructor that will do that (by default one that initializes all the fields to their default value is created)</li></ul>



<p><br>Here is the illustration with the equivalent code:</p>


<pre class="brush: plain; title: ; notranslate">
using static System.Console;

void f() {
	WriteLine(&quot;Write data to the stack&quot;);
	
	A a;
	a.N = 123;
	
	B b;
	b.N = 456;
	
	WriteLine($&quot;a.N: {a.N}&quot;);
	WriteLine($&quot;b.N: {b.N}&quot;);
}

void g() {
	WriteLine(&quot;Without explicit constructor call&quot;);
	
	A a;
	B b;
	
	WriteLine($&quot;a.N: {a.N}&quot;);
	WriteLine($&quot;b.N: {b.N}&quot;);
}

void h() {
	WriteLine(&quot;With explicit constructor call&quot;);
	
	A a = new A();
	B b = new B();
	
	WriteLine($&quot;a.N: {a.N}&quot;);
	WriteLine($&quot;b.N: {b.N}&quot;);
}

f();
g();
h();

struct A {
	public int N;	
}

struct B {
	public int N;
	
	public B() {
	}
}
</pre>


<p>It&#8217;s OK for method <code>f</code> as the fields are initialized right after allocation of the instances.<br>But not for method <code>g</code> which won&#8217;t compile:</p>



<pre class="wp-block-preformatted">&gt;csc Test.cs
 Compilateur Microsoft (R) Visual C# version 4.4.0-3.22518.13 (7856a68c)
 Copyright (C) Microsoft Corporation. Tous droits réservés.
 Test.cs(17,20): error CS0170:  Use of possibly unassigned field 'N'
 Test.cs(18,20): error CS0170:  Use of possibly unassigned field 'N'</pre>



<p>And without the <code>g</code> method:</p>



<pre class="wp-block-preformatted">&gt;csc Test.cs
 Compilateur Microsoft (R) Visual C# version 4.4.0-3.22518.13 (7856a68c)
 Copyright (C) Microsoft Corporation. Tous droits réservés.
&gt;Test.exe
 Write data to the stack
 a.N: 123
 b.N: 456
 With explicit constructor call
 a.N: 0
 b.N: 0</pre>



<p>All the memory has been zeroed out, nothing falling through any crack.</p>



<h2>Default constructor invocation</h2>



<h3>C++</h3>



<p>In C++ the default constructor is called after the memory to store the object has been allocated, be it inside an array, for each one of its elements, or inside another object:</p>


<pre class="brush: cpp; title: ; notranslate">
#include &lt;iostream&gt;

struct A {
	A()	{
		std::cout &lt;&lt; &quot;\tA()&quot; &lt;&lt; std::endl;
	}
};

struct B {
	A a;
};

int main() {
	std::cout &lt;&lt; &quot;1. Allocation on the stack without call to constructor&quot; &lt;&lt; std::endl;
	A a;
	
	std::cout &lt;&lt; &quot;2. Allocation in an array allocated on the stack&quot; &lt;&lt; std::endl;
	A as[3];
	
	std::cout &lt;&lt; &quot;3. Allocation in an array allocated on the heap&quot; &lt;&lt; std::endl;
	A* ash = new A[3];
	
	std::cout &lt;&lt; &quot;4. Allocation in a class instance allocated on the stack&quot; &lt;&lt; std::endl;
	B bs;
	
	std::cout &lt;&lt; &quot;5. Allocation in a class instance allocated on the heap&quot; &lt;&lt; std::endl;
	B* bh = new B();
	
	std::cout &lt;&lt; &quot;6. Allocation in an array allocated on the heap with default instanciation&quot;  &lt;&lt; std::endl;
	A ase[] = { {}, {}, {} };
	
	std::cout &lt;&lt; &quot;7. Allocation on the stack with call to constructor&quot; &lt;&lt; std::endl;
	A ac = A();

	std::cout &lt;&lt; &quot;8. Allocation in an array allocated on the heap with call to constructor&quot; &lt;&lt; std::endl;
	A asc[] = { A(), A(), A() };
	
	return 0;
}
</pre>


<p>Compilation:</p>



<pre class="wp-block-preformatted">&gt;cl /EHsc test.cpp</pre>



<p>Run:</p>



<pre class="wp-block-preformatted">&gt;test.exe
1. Allocation on the stack without call to constructor
     A()
2. Allocation in an array allocated on the stack
     A()
     A()
     A()
3. Allocation in an array allocated on the heap
     A()
     A()
     A()
4. Allocation in a class instance allocated on the stack
     A()
5. Allocation in a class instance allocated on the heap
     A()
6. Allocation in an array allocated on the heap with default instanciation
     A()
     A()
     A()
7. Allocation on the stack with call to constructor
     A()
8. Allocation in an array allocated on the heap with call to constructor
     A()
     A()
     A()</pre>



<p>The default constructor is called every time.</p>



<p>As for case #6 not sure this is a perfect equivalent of the C# <code>default</code> operator which returns the default value for any type, e.g. 0 for <code>int</code>, and a zeroed instance for <code>struct</code>s.</p>



<h3>C#</h3>



<p>In C# again things are different, the default constructor is never called implicitly if the object is allocated inside another, it must be called explicitly :</p>


<pre class="brush: csharp; title: ; notranslate">
using System;
using static System.Console;

WriteLine(&quot;1. Allocation on the stack without call to constructor&quot;);
A a;
	
WriteLine(&quot;2. Allocation in an array allocated on the stack&quot;);
Span&lt;A&gt; @as = stackalloc A[3];
	
WriteLine(&quot;3. Allocation in an array allocated on the heap&quot;);
A[] ash = new A[3];
	
WriteLine(&quot;4. XXX&quot;);
	
WriteLine(&quot;5. Allocation in a class instance allocated on the heap&quot;);
B bh = new B();

WriteLine(&quot;6. Allocation in an array allocated on the heap with default instanciation&quot;);
A[] ase = { default(A), default(A), default(A) };

WriteLine(&quot;7. Allocation on the stack with call to constructor&quot;);
A ac = new A();

WriteLine(&quot;8. Allocation in an array allocated on the heap with call to constructor&quot;);
A[] asc = { new A(), new A(), new A() };

struct A
{
	public A() =&gt; WriteLine(&quot;\tA()&quot;);
}

class B
{
	A a;
}
</pre>


<p>Some remarks:</p>



<ul><li>for <strong>.NET Framework</strong> (should be transparent in <strong>.NET Core</strong>) to get and use the <code>Span&lt;&gt;</code> type you must use <strong>NuGet</strong> package <strong>System.Memory</strong> (I&#8217;ve used version 4.5.5) and <strong>System.Runtime.CompilerServices.Unsafe</strong> (version 4.5.3 which is the one expected by the version of System.Memory)</li><li>Case #4 is not possible as <code>B</code> is a reference type so its instances can&#8217;t be allocated on the stack</li></ul>



<p>Compilation:</p>



<pre class="wp-block-preformatted">&gt;csc /reference:System.Memory.dll Test.cs
 Compilateur Microsoft (R) Visual C# version 4.4.0-3.22518.13 (7856a68c)
 Copyright (C) Microsoft Corporation. Tous droits réservés.
 Test.cs(9,3): warning CS0168: The variable 'a' is declared, but never used
 Test.cs(39,4): warning CS0169: Field 'B.a' is never used</pre>



<p>Run:</p>



<pre class="wp-block-preformatted">&gt;Test.exe
1. Allocation on the stack without call to constructor
2. Allocation in an array allocated on the stack
3. Allocation in an array allocated on the heap
4. XXX
5. Allocation in a class instance allocated on the heap
6. Allocation in an array allocated on the heap with default instanciation
7. Allocation on the stack with call to constructor
     A()
8. Allocation in an array allocated on the heap with call to constructor
     A()
     A()
     A() </pre>



<p>The default constructor is only called when explicitly called.</p>



<p>And previous to C# 10.0 it was even prohibited to define a default constructor for <code>struct</code>s:</p>



<pre class="wp-block-preformatted">&gt;csc /reference:System.Memory.dll -langversion:9.0 Test.cs
 Compilateur Microsoft (R) Visual C# version 4.4.0-3.22518.13 (7856a68c)
 Copyright (C) Microsoft Corporation. Tous droits réservés.
 Test.cs(34,9): error CS8773: Feature 'parameterless struct constructors' is not available in C# 9.0. Please use language version 10.0 or greater. </pre>



<p>It was by design to avoid wrong expectations like it being called when allocating an array of instances.</p>



<h2>Conclusion</h2>



<p>This article has illustrated the different design choices made for <strong>C++</strong> and <strong>.NET/C#</strong> regarding objects creation.</p>



<p>There is far more to say concerning the differences between C++ and .NET/C# but objects creation is a tricky topic which can get in the way if not well understood.</p>



<p>Comparing the languages allows putting into perspective some behaviours to understand that they are not due to technical limitations but merely to deliberate choices at the inception of the language.<br>And that these behaviours can change as the language gets more mature like C# now supporting <strong>default constructors</strong> for <code>struct</code>s.</p>
]]></content:encoded>
							<wfw:commentRss>http://pragmateek.com/objects-creation-in-cs-vs-cpp/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
							</item>
		<item>
		<title>Beware of too concise code</title>
		<link>http://pragmateek.com/beware-of-too-concise-code/</link>
				<comments>http://pragmateek.com/beware-of-too-concise-code/#comments</comments>
				<pubDate>Thu, 12 Sep 2019 11:15:37 +0000</pubDate>
		<dc:creator><![CDATA[pragmateek]]></dc:creator>
				<category><![CDATA[.Net Development]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[async]]></category>
		<category><![CDATA[c#]]></category>

		<guid isPermaLink="false">http://pragmateek.com/?p=3617</guid>
				<description><![CDATA[Introduction As developers we often strive to build concise code in order to avoid useless ceremony that would distract from its purpose. We do that by leveraging the syntactic sugar offered by the languages to reduce code verbosity and increase &#8230; <a href="http://pragmateek.com/beware-of-too-concise-code/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
								<content:encoded><![CDATA[



<h2>Introduction</h2>



<p>As developers we often strive to build <strong>concise</strong> code in order to avoid useless ceremony that would distract from its purpose.</p>



<p>We do that by leveraging the<strong> syntactic sugar</strong> offered by the languages to reduce code <strong>verbosity</strong> and increase its <strong>expressiveness</strong> but it can become a trap and lead to code that does not do what is expected.</p>



<p>In this article, I&#8217;ll illustrate this point with a powerful <strong>C#</strong> feature: <strong>async methods</strong>.</p>



<span id="more-3617"></span>



<h2>An async parsing method</h2>



<p>Here is an async method that parses integers:</p>


<pre class="brush: csharp; title: ; notranslate">
static async Task&lt;int&gt; ParseInt(string s)
{
    Console.WriteLine($&quot;Start parsing '{s}'.&quot;);
    await Task.Delay(1);
    Console.WriteLine($&quot;End parsing '{s}'.&quot;);
    return int.Parse(s);
}
</pre>


<p>As it is a &#8220;pure&#8221; function, calls are independent and can be executed <strong>in parallel</strong>.</p>



<h2>A (too) concise code</h2>



<p>And here is a naive usage of it:</p>


<pre class="brush: csharp; title: ; notranslate">
static async Task TestParallelismKO()
{
    int sum = await ParseInt(&quot;1&quot;) + await ParseInt(&quot;2&quot;) + await ParseInt(&quot;3&quot;);

    Console.WriteLine($&quot;Sum is {sum}&quot;);
}
</pre>


<p>The output is disappointing:</p>


<pre class="brush: plain; title: ; notranslate">
Start parsing '1'.
End parsing '1'.
Start parsing '2'.
End parsing '2'.
Start parsing '3'.
End parsing '3'.
Sum is 6
</pre>


<p>The result is correct but the calls are <strong>sequential</strong>!</p>



<h2>More verbosity to understand</h2>



<p>Here is a longer version that makes the root cause clear:</p>


<pre class="brush: csharp; title: ; notranslate">
static async Task TestParallelismKO_Verbose()
{
    var i1 = await ParseInt(&quot;1&quot;);
    var i2 = await ParseInt(&quot;2&quot;);
    var i3 = await ParseInt(&quot;3&quot;);

    int sum = i1 + i2 + i3;

    Console.WriteLine($&quot;Sum is {sum}&quot;);
}
</pre>


<p>So we are waiting for each parsing operation to be completed before jumping to the next.</p>



<h2>The fix</h2>



<p>Instead, we should:<br>1. First, run all the parsing tasks,<br>2. Then, wait for them to complete (whatever the order)</p>



<p>Here is an implementation of this:</p>


<pre class="brush: csharp; title: ; notranslate">
static async Task TestParallelismOK()
{
    var t1 = ParseInt(&quot;1&quot;);
    var t2 = ParseInt(&quot;2&quot;);
    var t3 = ParseInt(&quot;3&quot;);

    int sum = await t1 + await t2 + await t3;

    Console.WriteLine($&quot;Sum is {sum}&quot;);
}
</pre>


<p>And here is the output:</p>


<pre class="brush: plain; title: ; notranslate">
Start parsing '1'.
Start parsing '2'.
Start parsing '3'.
End parsing '3'.
End parsing '1'.
End parsing '2'.
Sum is 6
</pre>


<p>The calls are executed <strong>in parallel</strong> as expected.</p>



<h2>Conclusion</h2>



<p>Using syntactic sugar is great for <strong>readability</strong> and <strong>productivity</strong> but we must understand what is happening under the hood at the risk of writing incorrect code whose misbehaviour might be spotted later or even never.</p>
]]></content:encoded>
							<wfw:commentRss>http://pragmateek.com/beware-of-too-concise-code/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
							</item>
		<item>
		<title>When semicolons matter</title>
		<link>http://pragmateek.com/when-semicolons-matter/</link>
				<comments>http://pragmateek.com/when-semicolons-matter/#respond</comments>
				<pubDate>Fri, 06 Sep 2019 14:46:22 +0000</pubDate>
		<dc:creator><![CDATA[pragmateek]]></dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Node]]></category>

		<guid isPermaLink="false">http://pragmateek.com/?p=3601</guid>
				<description><![CDATA[Introduction Younger I was a dogmatic developer blindly enforcing the IT gurus&#8217; dogma, later I&#8217;ve become more pragmatic preferring code readability and maintainability.In JavaScript, it means omitting the semicolons to lighten the code and remove useless ceremony. But in some &#8230; <a href="http://pragmateek.com/when-semicolons-matter/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
								<content:encoded><![CDATA[



<h2>Introduction</h2>



<p>Younger I was a dogmatic developer blindly enforcing the IT gurus&#8217; dogma, later I&#8217;ve become more pragmatic preferring code readability and maintainability.<br>In <strong>JavaScript</strong>, it means omitting the <strong>semicolon</strong>s to lighten the code and remove useless ceremony.</p>



<p>But in some rare corner cases omitting a semicolon can completely change the way the compiler interprets the code.<br>Hopefully, it will cause a compilation error, and in the worst case a hidden bug hard to track.</p>



<p>In this article, I describe one of these corner cases.</p>



<span id="more-3601"></span>



<h2>A simple code</h2>



<p>Here is a basic JavaScript code snippet whose meaning is quite obvious for a human developer:</p>


<pre class="brush: jscript; title: ; notranslate">
var evens = [], odds = []

var n = 123

console.log(&quot;n is %s&quot;, n % 2 === 0 ? 'even' : 'odd')

(n % 2 === 0 ? evens : odds).push(n)
</pre>


<p>If <code>n</code> is even it is added to the <code>evens</code> array, otherwise to the <code>odds</code> array.</p>



<h2>A strange error</h2>



<p>But compiling it raise a <code>TypeError</code>:</p>



<pre class="wp-block-preformatted">(n % 2 === 0 ? evens : odds).push(n)<br> ^<br> TypeError: console.log(…) is not a function<br>     at Object. (C:\Temp\test.js:7:1)<br>     at Module._compile (internal/modules/cjs/loader.js:701:30)<br>     at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)<br>     at Module.load (internal/modules/cjs/loader.js:600:32)<br>     at tryModuleLoad (internal/modules/cjs/loader.js:539:12)<br>     at Function.Module._load (internal/modules/cjs/loader.js:531:3)<br>     at Function.Module.runMain (internal/modules/cjs/loader.js:754:12)<br>     at startup (internal/bootstrap/node.js:283:19)<br>     at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)</pre>



<p>The error is telling that we cannot call the return value of <code>console.log</code> as it is not a function!</p>



<p>Apparently, the compiler has misunderstood our intent.</p>



<h2>What the compiler sees</h2>



<p>Indeed here is how the compiler interprets the last lines:</p>


<pre class="brush: jscript; title: ; notranslate">
console.log(&quot;n is %s&quot;, n % 2 === 0 ? 'even' : 'odd')(n % 2 === 0 ? evens : odds).push(n)
</pre>


<p>Not the same meaning at all, here the call to the return value of <code>console.log</code> is obvious.</p>



<h2>Clarifying our intent</h2>



<p>To help the compiler understand that we have two separate instructions we must separate them with a <strong>semicolon</strong>:</p>


<pre class="brush: jscript; title: ; notranslate">
console.log(&quot;n is %s&quot;, n % 2 === 0 ? 'even' : 'odd');

(n % 2 === 0 ? evens : odds).push(n)
</pre>


<p>Now the code runs as expected pushing <code>n</code> to the relevant array.</p>



<h2>Conclusion</h2>



<p>Even after years of practice JavaScript can still surprise you with subtle errors you would not get in other languages.</p>



<p>Let&#8217;s say this is what makes it somehow flavorful. <img src="https://s.w.org/images/core/emoji/12.0.0-1/72x72/1f609.png" alt="😉" class="wp-smiley" style="height: 1em; max-height: 1em;" /></p>
]]></content:encoded>
							<wfw:commentRss>http://pragmateek.com/when-semicolons-matter/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
							</item>
		<item>
		<title>A basic use-case for Task Unwrap</title>
		<link>http://pragmateek.com/a-basic-use-case-for-task-unwrap/</link>
				<comments>http://pragmateek.com/a-basic-use-case-for-task-unwrap/#comments</comments>
				<pubDate>Sun, 18 Aug 2019 23:31:16 +0000</pubDate>
		<dc:creator><![CDATA[pragmateek]]></dc:creator>
				<category><![CDATA[.Net Development]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Promise]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[dotnet]]></category>
		<category><![CDATA[Task]]></category>
		<category><![CDATA[TPL]]></category>
		<category><![CDATA[Unwrap]]></category>

		<guid isPermaLink="false">http://pragmateek.com/?p=3564</guid>
				<description><![CDATA[Introduction Recently, after months without using .Net/C#, I was enhancing an existing .Net/C# WPF application leveraging the .Net Task Parallel Library (TPL). But naively applying the JavaScript Promises patterns I had used in the previous months I was bitten by &#8230; <a href="http://pragmateek.com/a-basic-use-case-for-task-unwrap/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
								<content:encoded><![CDATA[



<h2>Introduction</h2>



<p>Recently, after months without using <strong>.Net/C#</strong>, I was enhancing an existing .Net/C# <strong>WPF</strong> application leveraging the .Net <strong>Task Parallel Library</strong> (<strong>TPL</strong>).</p>
<p>But naively applying the <strong>JavaScript Promises</strong> patterns I had used in the previous months I was bitten by a strange issue which forced me to use the quite exotic <strong><code>Unwrap</code></strong> extension method.</p>
<p>This article describes the issue, explains its cause, provides a fix with <code>Unwrap</code>, and finally provides a more modern version with the <strong>C# 5.0</strong> <strong>async/await</strong> paradigm.</p>



<span id="more-3564"></span>



<h2>A simple workflow in JavaScript with Promises</h2>



<p>Here is a JavaScript implementation of a simple workflow with 3 steps, the second one simulating a delayed processing with <strong><code>setTimeout</code></strong>, using the <strong>Promise</strong> API:</p>



<pre class="wp-block-code"><code>function doFirstThing() {
	return new Promise(resolve => {
		console.log("First thing done")
		resolve()
	})
}

function doSecondThing() {
	return new Promise(resolve => {
		setTimeout(() => {
			console.log("Second thing done")
			resolve()
		}, 1000)
	})
}

function doThirdThing() {
	return new Promise(resolve => {
		console.log("Third thing done")
		resolve()
	})
}

doFirstThing().then(doSecondThing).then(doThirdThing)</code></pre>



<p>Here is the result once run with <strong>Node</strong>:</p>



<pre class="wp-block-code"><code>$ node test.js
First thing done
Second thing done
Third thing done</code></pre>



<h2>A C# implementation with Tasks</h2>



<p>Here is the same workflow implemented with <strong>C#</strong> using <strong>.Net TPL</strong>:</p>



<pre class="wp-block-code"><code>using System;
using System.Threading.Tasks;

namespace Test
{
    class Program
    {
        static Task DoFirstThing()
        {
            return Task.Run(() => Console.WriteLine("First thing done"));
        }

        static Task DoSecondThing()
        {
            return Task.Delay(1000).ContinueWith(_ => Console.WriteLine("Second thing done"));
        }

        static Task DoThirdThing()
        {
            return Task.Run(() => Console.WriteLine("Third thing done"));
        }

        static void Main(string[] args)
        {
            DoFirstThing().ContinueWith(_ => DoSecondThing()).ContinueWith(_ => DoThirdThing());

            Console.ReadLine();
        }
    }
}</code></pre>



<p>Note that contrary to <strong>JavaScript Promises</strong> <strong>.Net Tasks</strong> are not started/scheduled automatically when created, hence the need to explicitly call <strong><code>Run</code></strong>.</p>



<p>Here is the result:</p>



<pre class="wp-block-code"><code>First thing done
Third thing done
Second thing done</code></pre>



<p>As you see <u>the third step is executed before the second one!</u></p>



<p>This is because <strong><code>ContinueWith</code></strong> creates a new <strong><code>Task</code></strong> wrapping the provided treatment which only consists in calling <strong><code>DoSecondThing</code></strong> (which itself creates the second task) which returns immediately.</p>



<p><strong><code>ContinueWith</code></strong> won&#8217;t consider the resulting <strong><code>Task</code></strong>, contrary to <strong><code>Promise.then</code></strong> which handles the case of returning a <strong><code>Promise</code></strong> in a specific manner: the <strong><code>Promise</code></strong> returned by <strong><code>then</code></strong> will be resolved only when the underlying <strong><code>Promise</code></strong> will.</p>



<h2>Unwrap to the rescue</h2>



<p>To retrieve the JavaScript Promises behavior we need to explicitly tell the TPL we want to consider the underlying Task using <strong><code><a href="https://docs.microsoft.com/fr-fr/dotnet/api/system.threading.tasks.taskextensions.unwrap?view=netframework-4.8" target="_blank" rel="noopener noreferrer">Unwrap</a></code></strong> (implemented as an extension method provided by the <code><strong>TaskExtensions</strong></code> class):</p>



<pre class="wp-block-code"><code>DoFirstThing().ContinueWith(_ => DoSecondThing()).Unwrap().ContinueWith(_ => DoThirdThing());</code></pre>



<p>Result is now consistent with JavaScript:</p>



<pre class="wp-block-code"><code>First thing done
Second thing done
Third thing done</code></pre>



<h2>A more modern way with await</h2>



<p><strong>C# 5.0</strong> adds some syntactic sugar to ease the use of the TPL with the <strong><a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/await" target="_blank" rel="noopener noreferrer"><code>await</code> operator</a></strong>:</p>



<pre class="wp-block-code"><code>await DoFirstThing();
await DoSecondThing();
await DoThirdThing();</code></pre>



<p><strong><code>await</code></strong> internally calls <strong><code>Unwrap</code></strong> and waits on the underlying <strong><code>Task</code></strong> as expected, and yields the same result.</p>



<p>Note that <strong><code>await</code></strong> can only be used in an <strong><code>async</code></strong> method.</p>



<h2>Conclusion</h2>



<p>Mapping between languages and frameworks is not always obvious but fortunately nowadays all seem to copycat each other and they end offering the same paradigms and APIs like the <strong>async/await</strong> duo you use almost in the same manner in both <strong>C#</strong> and <strong>JavaScript</strong>.</p>
]]></content:encoded>
							<wfw:commentRss>http://pragmateek.com/a-basic-use-case-for-task-unwrap/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
							</item>
		<item>
		<title>Optional passed by reference parameters with C# for VBA COM APIs</title>
		<link>http://pragmateek.com/optional-passed-by-reference-parameters-with-c-for-vba-com-apis/</link>
				<comments>http://pragmateek.com/optional-passed-by-reference-parameters-with-c-for-vba-com-apis/#respond</comments>
				<pubDate>Sat, 05 Sep 2015 15:24:51 +0000</pubDate>
		<dc:creator><![CDATA[pragmateek]]></dc:creator>
				<category><![CDATA[.Net Development]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Excel development]]></category>
		<category><![CDATA[VBA]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[addins]]></category>
		<category><![CDATA[API]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[COM]]></category>
		<category><![CDATA[Excel]]></category>
		<category><![CDATA[Office]]></category>
		<category><![CDATA[pattern]]></category>
		<category><![CDATA[vba]]></category>
		<category><![CDATA[Visual Studio]]></category>

		<guid isPermaLink="false">http://pragmateek.com/?p=3443</guid>
				<description><![CDATA[Introduction If you&#8217;ve already developed COM APIs with .Net, typically in C# with VBA as the consuming language, you&#8217;ve probably leveraged two powerful features: by-reference parameter passing that allows the API to change the input object itself, not only its &#8230; <a href="http://pragmateek.com/optional-passed-by-reference-parameters-with-c-for-vba-com-apis/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
								<content:encoded><![CDATA[<p></p>
<h1>Introduction</h1>
<p class="small-margin-bottom">If you&#8217;ve already developed <strong>COM APIs</strong> with <strong>.Net</strong>, typically in <strong>C#</strong> with <strong>VBA</strong> as the consuming language, you&#8217;ve probably leveraged two powerful features:</p>
<ul class=>
<li><strong>by-reference parameter passing</strong> that allows the API to change the input object itself, not only its content.<br />
This is marked with <strong><code>ref</code></strong> in C#:</p>
<pre class="brush: csharp; title: ; notranslate">void LoadData(ref string data)</pre>
</li>
<li><strong>optional parameters</strong> that allow the caller to omit them when calling into the API:
<pre class="brush: csharp; title: ; notranslate">void SaveData(string data = &quot;DEFAULT&quot;)</pre>
</li>
</ul>
<p>Sometimes you want to have both for a parameter: the ability to omit it and to change it.<br />
This is something <strong>COM</strong> supports but unfortunately this is not supported by C#.<br />
Recently one of my customer needed precisely that for a COM API developed in C# migrated from <strong>VB6</strong> where it was plug-and-play.<br />
The original developers of the API had done a quick study and concluded that it was not possible with the new C# API and indeed it was not documented at all.<br />
From experience I know that COM is not used a lot today and that resources are scarce, so, to be sure, I&#8217;ve done my due diligence and reexamined the issue, digging a little deeper and testing undocumented stuff.<br />
I&#8217;ve finally found a solution that I would describe as a &#8220;trick&#8221;, because it&#8217;s not documented, and that I&#8217;ll present in detail in this article.<br />
<span id="more-3443"></span></p>
<h1>Some background</h1>
<h2>From source languages to .Net</h2>
<p>When you develop on the .Net platform all your <strong>source code</strong> (be it <strong>C#</strong>, <strong>VB.Net</strong>, <strong>C++/CLI</strong>, <strong>F#</strong>&#8230;) is compiled by your <strong>language compiler</strong> to a <strong>common binary intermediate language</strong>, a <strong>byte-code</strong>, called <strong>CIL</strong>, which is itself compiled at runtime (or before but that&#8217;s another story) to <strong>native binary code</strong> by the <strong>virtual machine</strong>, the <strong>CLR</strong> (more precisely by its own <strong>native compiler</strong> the <strong>JITter</strong>).<br />
So each language structure, like <strong>optional parameters</strong>, is mapped to a common format.<br />
So when you use C# as your source language and define <strong>optional parameters with a default value</strong>, the C# compiler (CSC) will translate them into something usable from other .Net components that may not have been developed in C#: some <strong>metadata</strong> expressed as what is called <strong>.Net attributes</strong>.<br />
More concretely when you write this in C#:</p>
<pre class="brush: csharp; title: ; notranslate">void SaveData(string data = &quot;DEFAULT&quot;)</pre>
<p>the C# compiler will generate this:</p>
<pre class="brush: plain; title: ; notranslate">.method public hidebysig instance void
        SaveData([opt] string data) cil managed
{
  .param [1] = &quot;DEFAULT&quot;</pre>
<p>(more exactly the binary form of this)<br />
The nature of the <code>data</code> parameter is specified through 2 <strong>metadata</strong>:<br />
&#8211; <strong><code>[opt]</code></strong> that marks the parameter as <strong>optional</strong>,<br />
&#8211; <strong><code>.param</code></strong> that stores the default value used when the parameter is not provided<br />
These metadata can be interpreted by many tools, like <strong>compilers</strong>.</p>
<h2>Directly specifying the metadata into the source code</h2>
<p>The .Net class library allows us to directly specify these metadata without using specific language construct:<br />
&#8211; <strong><code>[opt]</code></strong> via the <strong><code>[OptionalAttribute]</code></strong> attribute<br />
&#8211; <strong><code>.param</code></strong> via the <strong><code>[DefaultParameterValueAttribute]</code></strong> attribute<br />
Both these attributes are in the <strong><code>System.Runtime.InteropServices</code></strong> namespace.<br />
Using them we can obtain exactly the same .Net <strong>CIL</strong> code as before without using C# constructs:</p>
<pre class="brush: csharp; title: ; notranslate">void SaveData2([Optional] [DefaultParameterValue(&quot;DEFAULT&quot;)] string data)</pre>
<p>The result is the same as above:</p>
<pre class="brush: plain; title: ; notranslate">.method public hidebysig instance void
        SaveData2([opt] string data) cil managed
{
  .param [1] = &quot;DEFAULT&quot;</pre>
<p>This is more verbose and less readable so you would not use it in standard situations where your source language provides syntactic sugar like C# does.</p>
<h2>Tricking C#</h2>
<p>Where it becomes interesting is that as you don&#8217;t use the C# language constructs you are no more constrained by them.<br />
In our case we can get rid of the C# limitation concerning optional passed by reference parameters and write something like:</p>
<pre class="brush: csharp; title: ; notranslate">public static string MirrorOrDefault([Optional] [DefaultParameterValue(&quot;DEFAULT&quot;)] ref string data)
{
    return data;
}</pre>
<p>which is equivalent to:</p>
<pre class="brush: csharp; title: ; notranslate">public static string MirrorOrDefault(ref string data = &quot;DEFAULT&quot;)</pre>
<p>which is illegal in C# (at least in current versions).<br />
If this method is called from C# you&#8217;ll always have to pass the parameter explicitly, defeating the purpose of the trick.<br />
But if called from another environment it will allow you to have <strong>optional passed-by-reference parameters</strong>.<br />
Here is a sample in VB.Net that illustrates this ability:</p>
<pre class="brush: vb; title: ; notranslate">Imports System

Class Program
	Shared Sub Main()
		Dim result As String
		result = OptionalByRefInCS.MirrorOrDefault()
		
		Console.WriteLine(result)
	End Sub
End Class</pre>
<p>The calling code doesn&#8217;t specify the <code>data</code> parameter.<br />
Executing this produces this output:</p>
<pre class="brush: plain; title: ; notranslate">DEFAULT</pre>
<p>So the once C# code has been called with the default parameter value, &#8220;DEFAULT&#8221;, it has returned to the caller.<br />
We&#8217;ve bypassed the C# limitations by working directly at the .Net level with <strong>attributes</strong>.</p>
<h1>Application to VBA COM APIs</h1>
<h2>COM and .Net</h2>
<p>The above paragraph has illustrated a direct .Net component (written in VB.Net) to .Net component (written in C#) communication that only used the .Net plumbing.<br />
So the <strong>.Net metadata</strong> generated by the C# compiler were consumed by the <strong>VB.Net compiler</strong>.<br />
But when calling into .Net from outside .Net, like from <strong>VBA</strong> with a shared addin, we have another layer of infrastructure to consider: <strong>COM</strong>.<br />
Ans as COM comes with its own way of representing <strong>types</strong>, their <strong>methods</strong> and their <strong>parameters</strong>, including <strong>optional ones</strong>, we need to speak its language.<br />
Fortunately the tools provided by .Net to work with COM, like <strong>RegAsm</strong> and <strong>TLBExp</strong>, are able to interpret the <strong>.Net metadata</strong> to convert them into <strong>COM metadata</strong> that will themselves be consumed by the <strong>VBA</strong> infrastructure.<br />
All these <strong>COM metadata</strong> are stored in dedicated files: <strong>type libraries</strong> a.k.a. <strong>TLBs</strong>.</p>
<h2>A C# COM API</h2>
<p>To illustrate all these points we&#8217;ll build a simple <strong>C# API</strong> that will be consumed by <strong>VBA</strong> through <strong>COM</strong>.</p>
<div style="background: palegreen;border: dashed thin; padding: 10px;">
For a detailed introduction to <strong>COM addins in .Net</strong> read this article: <a href="http://pragmateek.com/extend-your-vba-code-with-c-vb-net-or-ccli/" title="Extend your VBA code with C#, VB.Net or C++/CLI" target="_blank"><strong>Extend your VBA code with C#, VB.Net or C++/CLI</strong></a>.
</div>
<p>
Here is the C# source code:</p>
<pre class="brush: csharp; title: ; notranslate">using System; // Random
using System.Runtime.InteropServices; // Guid, ClassInterface, ClassInterfaceType

[Guid(&quot;88FF845D-5283-4612-9F4B-1B8C5286A5DF&quot;)]
public interface IRainbowSource
{
    string NextColor([Optional] [DefaultParameterValue(&quot;Red&quot;)] ref string color);
	
    int CodeOf(string color);
}

[Guid(&quot;891CCD91-00F6-4C7C-86C0-8B8AF6C599B0&quot;)]
[ClassInterface(ClassInterfaceType.None)]
public class RainbowSource : IRainbowSource
{
	private static string[] colors = { &quot;Red&quot;, &quot;Orange&quot;, &quot;Yellow&quot;, &quot;Green&quot;, &quot;Blue&quot;, &quot;Indigo&quot;, &quot;Violet&quot; };
	
	private static int[] codes = { 3, 45, 6, 10, 41, 55, 13 };
	
	public string NextColor(ref string color)
	{
		string originalColor = color;
		
		int currentColorIndex = Array.IndexOf(colors, color);
		
		int nextColorIndex = (currentColorIndex + 1) % colors.Length;
		
		color = colors[nextColorIndex];
		
		return originalColor;
	}
	
	public int CodeOf(string color)
	{
		int colorIndex = Array.IndexOf(colors, color);
		
		return codes[colorIndex];
	}
}</pre>
<p>Don&#8217;t be distracted by the <strong>COM metadata</strong> and refer to the article mentioned above to fully understand them.<br />
The important part concerning our point is this method:</p>
<pre class="brush: csharp; title: ; notranslate">string NextColor([Optional] [DefaultParameterValue(&quot;Red&quot;)] ref string color);</pre>
<p>It uses the trick demonstrated above, but this time in an <strong>interface</strong> instead of a <strong>class</strong>.</p>
<p>Let&#8217;s <strong>compile it</strong>:</p>
<pre><strong style="font-size:large">csc /target:library UnicornAPI.cs</strong>
Microsoft (R) Visual C# Compiler version 4.0.30319.34209
for Microsoft (R) .NET Framework 4.5
Copyright (C) Microsoft Corporation. All rights reserved.
</pre>
<p>And <strong>register it for COM interop</strong>:</p>
<pre><strong style="font-size:large">regasm /tlb /codebase UnicornAPI.dll</strong>
Microsoft .NET Framework Assembly Registration Utility version 4.0.30319.34209
for Microsoft .NET Framework version 4.0.30319.34209
Copyright (C) Microsoft Corporation.  All rights reserved.
...</pre>
<p>Now let&#8217;s check the <strong>COM metadata</strong> generated by <strong>RegAsm</strong> (I&#8217;ve used <strong>OleView</strong>):</p>
<pre class="brush: plain; title: ; notranslate">[id(0x60020000)]
HRESULT NextColor([in, out, optional, defaultvalue(&quot;Red&quot;)] BSTR* color, [out, retval] BSTR* pRetVal);</pre>
<p class="small-margin-bottom">A bit verbose but we can see the essential for the <code>color</code> parameter:</p>
<ul>
<li>it is optional,</li>
<li>its default value is &#8220;Red&#8221;.</li>
</ul>
<h2>Using the API from VBA</h2>
<p>Here is what the <strong>VBE object browser</strong> has to say about the <code>NextColor</code> method:</p>
<pre class="brush: plain; title: ; notranslate">Function NextColor([color As String = &quot;Red&quot;]) As String
    Member of UnicornAPI.RainbowSource</pre>
<p>So the <code>color</code> parameter is correctly identified as optional with a default value of &#8220;Red&#8221; which is the value VBA will pass if we don&#8217;t provide any.<br />
And this is confirmed by VBE auto-completion if we start to write the code to call it:<br />
<div id="attachment_3459" style="width: 630px" class="wp-caption alignnone"><a href="http://pragmateek.com/wp-content/uploads/2015/08/Optional_by_ref_code_completion.png"><img aria-describedby="caption-attachment-3459" src="http://pragmateek.com/wp-content/uploads/2015/08/Optional_by_ref_code_completion.png" alt="VBA completion" width="620" height="196" class="size-full wp-image-3459" srcset="http://pragmateek.com/wp-content/uploads/2015/08/Optional_by_ref_code_completion.png 620w, http://pragmateek.com/wp-content/uploads/2015/08/Optional_by_ref_code_completion-300x95.png 300w, http://pragmateek.com/wp-content/uploads/2015/08/Optional_by_ref_code_completion-175x55.png 175w, http://pragmateek.com/wp-content/uploads/2015/08/Optional_by_ref_code_completion-500x158.png 500w" sizes="(max-width: 620px) 100vw, 620px" /></a><p id="caption-attachment-3459" class="wp-caption-text">VBE completion</p></div><br />
Finally here is a VBA sample code that leverages the API to demonstrate the behavior of the <code>NextColor</code> method:</p>
<pre class="brush: vb; title: ; notranslate">Sub MakeRainbows()
 Dim color As String
 Dim source As New UnicornAPI.RainbowSource
 color = source.NextColor
 Dim i As Long
 For i = 1 To 20
   Range(&quot;A1&quot;).Offset(i - 1).Interior.ColorIndex = source.CodeOf(color)
   Call source.NextColor(color)
 Next i
End Sub</pre>
<p class="small-margin-bottom">We get the expected behavior:</p>
<ul>
<li><code>color = source.NextColor</code>: if we don&#8217;t specify the parameter we get the default color &#8220;Red&#8221;,</li>
<li><code>Call source.NextColor(color)</code>: if we pass a color it is updated with the next color.</li>
</ul>
<h1>Some words of caution</h1>
<p>Be cautious when your code relies on <strong>the default value of the type</strong>.<br />
Indeed the default value you get if not specified in your <strong>C#</strong> source code through the <strong><code>[DefaultParameterValue]</code> attribute</strong> may not be what you expect.<br />
e.g. with a <code>DateTime</code> you won&#8217;t get the <strong>.Net</strong> <code>DateTime</code> <strong>default value</strong> <code>0001-01-01</code> but the <strong>VBA default value</strong> <code>1899-12-30</code> because, as in C#, this is the caller that sends the default value.<br />
And AFAIK there is no way to get around it because you can&#8217;t specify the default value for a <code>DateTime</code> and can&#8217;t use a <strong>nullable DateTime</strong> (a.k.a. <code>DateTime?</code> in C#, a.k.a. <code>Nullable&lt;DateTime></code> in .Net) because it is a <strong>generic type</strong>, which is not supported by <strong>COM</strong>.<br />
So you must take care of mapping the VBA default value to a meaningful value for the rest of your code down the pipeline:</p>
<pre class="brush: csharp; title: ; notranslate">public DateTime NextDate(ref DateTime date)
{
    DateTime originalDate = date != new DateTime(1899, 12, 30) ? (DateTime)date : DateTime.Today;
		
    date = originalDate.AddDays(+1);
		
    return originalDate;
}</pre>
<p>The problem is if the default VBA value can be a meaningful value for your function, so that you are not able to tell if the user has not passed anything or has passed the VBA default.<br />
AFAIK there is only one simple solution (without tweaking the <strong>IDL</strong>): using a <strong><code>Variant/Object</code></strong> instead of a <code>DateTime</code>.<br />
In the function you can check for the special value provided when the user has not provided the value: <code>Type.Missing</code> (a.k.a <code>System.Reflection.Missing.Value</code>):</p>
<pre class="brush: csharp; title: ; notranslate">public DateTime NextDate(ref object date)
{
    DateTime originalDate = date != Type.Missing ? (DateTime)date : DateTime.Today;
		
    date = originalDate.AddDays(+1);
		
    return originalDate;
}</pre>
<p>This makes the API less self-documenting because the expected type is not explicit but the name of the parameter should be enough to make clear what is expected.</p>
<h1>Conclusion</h1>
<p>As demonstrated in the last section this solution is not perfect but even if it&#8217;s not documented it does the job and is robust.<br />
You just have to be cautious and to do your due diligence by testing it with your real use-case to ensure it works seamlessly.</p>
<p>Recently I&#8217;ve again done my due diligence and shared this with the community on <a href="http://stackoverflow.com" title="StackOverflow" target="_blank">StackOverflow</a>: <a href="http://stackoverflow.com/questions/32169285/possible-nasty-side-effects-of-tricking-net-to-have-optional-ref-parameters-for" title="Possible nasty side effects of tricking .Net to have optional ref parameters for COM" target="_blank">Possible nasty side effects of tricking .Net to have optional ref parameters for COM</a>.<br />
I was pleased to get an answer from a COM guru, <a href="http://stackoverflow.com/users/17034/hans-passant" title="Hans Passant SO profile" target="_blank">Hans Passant</a> which I&#8217;ve found comforting as it did not point any nasty possible side effect but confirmed that default values may not be obvious.</p>
<p>As always if you catch any typo or mistake, encounter any issue or have additional questions feel free to let a comment, I’ll do my best to answer in a timely manner.</p>
]]></content:encoded>
							<wfw:commentRss>http://pragmateek.com/optional-passed-by-reference-parameters-with-c-for-vba-com-apis/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
							</item>
		<item>
		<title>[FRENCH] Est-ce la fin de WPF: présent et futur de WPF</title>
		<link>http://pragmateek.com/french-est-ce-la-fin-de-wpf-present-et-futur-de-wpf/</link>
				<comments>http://pragmateek.com/french-est-ce-la-fin-de-wpf-present-et-futur-de-wpf/#comments</comments>
				<pubDate>Sat, 13 Sep 2014 13:57:51 +0000</pubDate>
		<dc:creator><![CDATA[pragmateek]]></dc:creator>
				<category><![CDATA[.Net Development]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[WinRT]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[API]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[certification]]></category>
		<category><![CDATA[COM]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[pattern]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[winrt]]></category>
		<category><![CDATA[XAML]]></category>

		<guid isPermaLink="false">http://pragmateek.com/?p=3403</guid>
				<description><![CDATA[Introduction En tant que développeur et formateur WPF depuis plusieurs années les nouvelles orientations de Microsoft pour les plateformes clientes, avec la montée en puissance du tout nouveau WinRT, m&#8217;ont quelque peu inquiétées. Et pour cause : j&#8217;ai directement subi &#8230; <a href="http://pragmateek.com/french-est-ce-la-fin-de-wpf-present-et-futur-de-wpf/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
								<content:encoded><![CDATA[<p></p>
<h1>Introduction</h1>
<p>En tant que développeur et formateur <strong>WPF</strong> depuis plusieurs années les nouvelles orientations de Microsoft pour les <strong>plateformes clientes</strong>, avec la montée en puissance du tout nouveau <strong>WinRT</strong>, m&#8217;ont quelque peu inquiétées.</p>
<p>Et pour cause : j&#8217;ai directement subi l&#8217;échec et l&#8217;abandon de <strong>Silverlight</strong> et comme dit le proverbe &#8220;chat échaudé craint l&#8217;eau froide&#8221;.<br />
Depuis 2009 j&#8217;ai beaucoup investi, personnellement et professionnellement, dans WPF, l&#8217;utilisant pour développer des <strong>applications LOB</strong> dans le secteur financier, et désormais je dispense même des formations sur le sujet.<br />
Par conséquent le futur de WPF est critique pour moi, c&#8217;est pourquoi j&#8217;ai étudié cette question de l&#8217;avenir de WPF plus en détails, mettant en oeuvre mon expertise sur le sujet et ma récente découverte de WinRT.</p>
<p>Dans cet article je partagerai avec vous les résultats de cette &#8220;étude&#8221; en toute objectivité et transparence, afin de vous aider en tant que partie prenante dans votre veille technologique.<br />
J&#8217;espère que vous fournirez vos propres informations, afin que la communauté toute entière puisse avoir une meilleure vision des perspectives pour WPF.<br />
Dans la dernière partie de l&#8217;article je fournis des stratégies pour les entreprises et les développeurs utilisant WPF.</p>
<p><span id="more-3403"></span></p>
<h1>Des raisons de s&#8217;inquiéter</h1>
<p>Je commence par vous présenter les signes qui m&#8217;inquiètent, et devraient également vous inquiéter si vous êtes partie prenante WPF.</p>
<h2>Le blog de l&#8217;équipe WPF est inactif</h2>
<p>Comme toute équipe technique Microsoft, l&#8217;équipe responsable du développement de WPF possède <a href="http://blogs.msdn.com/b/wpf/" title="Blog de l'équipe WPF" target="_blank"><strong>un blog</strong></a> où ses membres partagent avec la communauté leur expertise WPF.<br />
Le dernier article de ce blog a été publié en mai 2011 soit <strong>il y a plus de 3 ans</strong>, précisément au moment où <strong>WinRT</strong> commençait à apparaître comme le prochain projet majeur de Microsoft.<br />
Un blog inactif peut signifier beaucoup de choses mais à mon avis rien de bon : très probablement l&#8217;équipe a été dégraissée au strict minimum et l&#8217;animation du blog n&#8217;est plus une priorité, peut être que les meilleurs éléments ont été affectés à d&#8217;autres projets comme WinRT, et peut être est-ce intentionnel pour envoyer un signal à la communauté&#8230;</p>
<p>En termes de communication un blog actif est essentiel car il montre que la technologie évolue et est développée par des développeurs enthousiastes et fiers de leur travail souhaitant partager avec la communauté.<br />
Il faut noter que souvent les blogs MSDN ne sont pas des plus actifs, celui d&#8217;Entity Framework faisant exception, grâce à Rowan Miller qui publie régulièrement de nouveaux articles, et c&#8217;est l&#8217;une des raisons pour lesquelles j&#8217;apprécie cette technologie : elle est développée par des gens brillants et investis.</p>
<h2>Le toolkit officiel n&#8217;est plus développé</h2>
<p>Le <a href="https://wpf.codeplex.com/" title="Le toolkit WPF" target="_blank"><strong>Toolkit WPF</strong></a> est un projet gratuit et open-source développé par les équipes de Microsoft et conçu pour servir d&#8217;antichambre aux versions officielles de WPF.<br />
Par exemple la <strong><code>DataGrid</code></strong> ne faisait pas partie de la version initiale de WPF (3.0 + 3.5) mais était disponible via le toolkit, et elle ne fût ajoutée officiellement qu&#8217;à partir de WPF 4.<br />
Le toolkit a fait son office jusqu&#8217;en 2010, mais depuis le projet est inactif, donc il semblerait qu&#8217;il n&#8217;y ait plus grand chose en magasin pour une éventuelle prochaine version de WPF.<br />
Signe de cette inactivité : la recherche &#8220;WPF Toolkit&#8221; sur Google classe le toolkit officiel second après un non-officiel (je reviendrai sur celui-ci dans la seconde partie de l&#8217;article).</p>
<h2>Plus de certification</h2>
<p>La <strong>certification WPF officiel</strong> (<strong>70-511</strong>) ne sera pas prolongée et <strong>arrivera à expiration à l&#8217;été 2015</strong>.<br />
C&#8217;est sans doute l&#8217;un des signes les plus forts envoyés aux développeurs WPF : ils ne devraient pas investir plus de temps dans cette technologie et au contraire devraient consacrer du temps à <strong>WinRT</strong> qui lui bénéficie d&#8217;un <strong>nouveau cycle de certification</strong>.<br />
Peut-être que Microsoft renoncera et repoussera un peu ce retrait comme cela a été le cas pour d&#8217;autres certifications après que les développeurs se soient plaints, mais cela ne changera rien au fait que WPF n&#8217;est plus la priorité.</p>
<p>Personnellement j&#8217;hésite encore à la passer tout simplement parce que j&#8217;ai peu de garantie que le temps et l&#8217;argent (oui en tant qu&#8217;entrepreneur c&#8217;est bibi qui paye) dépensés valent le coup.<br />
Pour le moment je préfère monter en compétences sur WinRT et préparer les certifications qui y sont dédiées et qui devraient être valables encore de nombreuses années.</p>
<h2>Pas d&#8217;intégration Windows 8</h2>
<p>Pour ceux qui se souviennent de la sortie de <strong>WPF 4</strong>, une grande partie des nouvelles fonctionnalités étaient dédiées à <strong>l&#8217;intégration Windows 7</strong> comme la personnalisation des éléments de la barre des tâches (jump-lists, progression, overlay&#8230;).<br />
Ce ne fût pas le cas avec <strong>WPF 4.5</strong> qui ne bénéficie pas d&#8217;un tel effort d&#8217;intégration avec les nouvelles fonctions de <strong>Windows 8+</strong> comme la charm-bar et les nombreux contrats applicatifs, bien qu&#8217;il y ait des interfaces d&#8217;interopérabilité.<br />
Si Microsoft n&#8217;a pas investit dans cette intégration cela démontre clairement que WPF n&#8217;est plus une technologie de 1<sup>er</sup> ordre au sein de Windows et que tout l&#8217;effort de développement est concentré sur WinRT, ce qui à mon avis est une décision sensée.</p>
<h2>Pas de support Windows RT</h2>
<p>Microsoft, historiquement un <strong>vendeur de logiciel</strong>, diversifie ses activités en devenant un <strong>vendeur de matériel</strong>, imitant ainsi ses concurrents Apple et Samsung.<br />
A cette fin Microsoft a acquis <strong>Nokia</strong> afin de bénéficier de sa présence historique sur <strong>le marché de la téléphonie mobile</strong>.<br />
Côté <strong>tablettes</strong> et <strong>ordinateurs portables</strong>, pour concurrencer les tablettes Apple <strong>iPad</strong> ainsi que ses ordinateurs portables <strong>MacBook Pros</strong>, Microsoft a lancé la gamme <strong>Surface</strong>.<br />
Il y a 2 déclinaisons des <strong>Surface 1</strong> et <strong>2</strong> en fonction de l&#8217;architecture matérielle : <strong>x86</strong> et <strong>ARM</strong>, ce dernier bénéficiant d&#8217;une verison dédiée de Windows : <strong>Windows RT</strong> (à ne pas confondre avec WinRT qui est une couche logicielle commune).<br />
Mais Windows RT ne supporte pas (du moins officiellement) les anciennes APIs comme le bon vieux <strong>Win32</strong>, et donc ne supporte pas toutes ses &#8220;surcouches&#8221; comme <strong>WinForms</strong> et &#8230; <strong>WPF</strong>, donc il n&#8217;est pas possible d&#8217;exécuter des applications WPF sur toutes les versions de la Surface.<br />
Et si Microsoft n&#8217;a pas investit dans cette compatibilité c&#8217;est aussi parce qu&#8217;il tente de se débarrasser de Win32 qui doit être remplacé par WinRT qui est spécialement conçu pour répondre aux nouveaux besoins.</p>
<h2>La nouvelle stratégie de Microsoft</h2>
<p>En février 2014 Microsoft nomma un nouveau <strong>CEO</strong>, <strong>Satya Nadella</strong>, qui est issu du <strong>département cloud</strong> de Microsoft.<br />
Il a remplacé <strong>Steve Ballmer</strong>, qui n&#8217;avait pas pris la mesure du marché du mobile (d&#8217;abord <a href="https://www.youtube.com/watch?v=eywi0h_Y5_U" title="Ballmer à propos de l'iPhone" target="_blank"><strong>l&#8217;iPhone</strong></a> puis <a href="https://www.youtube.com/watch?v=MTX1e-pMN6E" title="Ballmer à propos d'Android" target="_blank"><strong>Android</strong></a>) ce qui est probablement l&#8217;une des raisons pour lesquelles Microsoft a complètement raté le coche et doit désormais se battre pour se faire une place en grapillant pourcent après pourcent des parts de marché à la concurrence (Apple, Samsung).<br />
En opposition avec son prédécesseur la nouvelle stratégie globale pour Microsoft de Satya Nadella est &#8220;<strong>cloud first and mobile first</strong>&#8220;, mettant donc de côté le modèle traditionnel PC de bureau, et de nouveau c&#8217;est une stratégie des plus sensée.<br />
Mais WPF a précisément été conçu pour le &#8220;vieux&#8221; modèle : celui des applications de bureau dites &#8220;lourdes&#8221;, alors que WinRT répond à un modèle totalement différent, prenant en compte les nouveaux besoins mobiles.<br />
Bien sûr le marché du PC est loin d&#8217;être mort, mais il n&#8217;est plus désormais le modèle exclusif et prédominant.</p>
<h2>Le Windows Store</h2>
<p>Afin de capturer une part des revenus des vendeurs d&#8217;applications la plupart des propriétaires de plateformes logicielles comme <strong>Apple</strong> et <strong>Microsoft</strong> ont créé des &#8220;<strong>stores</strong>&#8221; par lesquels il faut passer pour publier et acheter les applications.<br />
Et malheureusement à ce que je sache les applications Windows Store doivent reposer sur WinRT, donc <strong>les applications WPF ne peuvent y être distribuées</strong>.<br />
Notez que ce n&#8217;est pas un souci pour les entreprises qui déploient leurs applications en interne et n&#8217;ont aucun besoin d&#8217;un store, ni pour les éditeurs de grosses applications professionnelles comme les ERPs qui utilisent leurs propres réseaux commerciaux pour vendre et déployer leurs applications, mais c&#8217;est un vrai problème pour les petits éditeurs, souvent individuels, qui ont besoin de la visibilité du store et ne pas l&#8217;utiliser c&#8217;est prendre le risque de se faire manger des parts de marchés par un concurrent.<br />
Désormais de plus en plus de personnes utilisent mécaniquement les stores pour rechercher de nouvelles applications donc il est impossible de passer à côté.<br />
Par conséquent si vous planifier de développer votre prochaine application en WPF vous risquez d&#8217;avoir de grandes difficultés à la distribuer, d&#8217;autant plus si vous comptez la vendre, donc vous devriez plutôt utiliser WinRT.</p>
<h2>La mobilité</h2>
<p>Vous consommez probablement une grosse partie des contenus digitaux via votre <strong>téléphone mobile</strong> en utilisant des applications web ou natives donc vous comprenez à quel point il est important aujourd&#8217;hui d&#8217;être présent sur le marché du mobile : il est quasi obligatoire de fournir une version mobile de vos applications.<br />
WPF n&#8217;a jamais été destiné au développement mobile et il n&#8217;est donc pas un acteur de ce marché, et pendant des années l&#8217;alternative mobile fût <strong>Silverlight for Windows Phone</strong> qui a été le support de référence jusqu&#8217;à Windows Phone 7.<br />
Mais utiliser un outil différent par plateforme est loin d&#8217;être idéal, bien qu&#8217;il était possible de partager la plupart du code procédural (C#) et de balisage (XAML).<br />
WinRT est une réponse à ce problème car il constitue un outil commun conçu pour faciliter le développement sur toutes les plateformes Windows qui sont elles-mêmes de plus en plus uniformisées au niveau même de l&#8217;OS avec Windows 8+.</p>
<p>A noter que pour un véritable développement multi-plateforme visant en plus <strong>Android</strong> et <strong>iOS</strong> Microsoft ne fournit aucun outil, et il faut se tourner vers <a href="http://xamarin.com/" title="Xamarin" target="_blank"><strong>Xamarin</strong></a> qui est un projet très prometteur.</p>
<h2>Les coûts de maintenance</h2>
<p>Si vous travaillez avec les technologies Microsoft depuis quelques années vous savez que Microsoft dépense son argent avec parcimonie, et pour de bonnes raisons : premièrement en tant qu&#8217;entreprise elle doit gagner de l&#8217;argent pour survivre, sans compter que de nos jours les actionnaires sont plus gourmands, donc un sou est un sou ; de plus la moindre petite fonctionnalité peut vite devenir très coûteuse parce que le processus de développement est très strict ; <em><strong>Eric Lippert</strong></em> en donne un aperçu dans cet article : <a href="http://blogs.msdn.com/b/ericlippert/archive/2003/10/28/53298.aspx" title="How many Microsoft employees does it take to change a lightbulb?" target="_blank">How many Microsoft employees does it take to change a lightbulb?</a><br />
Donc quand la communauté réclame une correction de bug ou une nouvelle fonctionnalité, l&#8217;implémentation n&#8217;en sera faite que si l&#8217;impact est conséquent :<br />
&#8211; soit d&#8217;une grande criticité comme une faille de sécurité, où même un nombre réduit de clients impactés justifie le développement<br />
&#8211; ou bien mineur mais gênant un grand nombre de personnes.<br />
Déveloper à la fois WPF et WinRT impliquerait de répondre à toutes les demandes de fonctionnalités et correction de bug des deux outils, ce qui n&#8217;est clairement pas envisageable, particulièrement en cette période de dégraissage chez Microsoft.</p>
<h2>Portabilité</h2>
<p>Ce qui aurait pu &#8220;sauver&#8221; WPF serait d&#8217;éventuels cas d&#8217;utilisation de <strong>niche</strong>, par exemple en tant qu&#8217;<strong>outil multiplateforme</strong> de développement d&#8217;applications client, mais ce n&#8217;est malheureusement pas le cas.<br />
Il y a bien une <strong>version multiplateforme de .Net</strong> (de la <strong>CLI</strong> pour être pointilleux) : <strong>Mono</strong>, qui tourne sous <strong>Windows</strong> bien sûr mais aussi sur <strong>Linux</strong>, <strong>Unix</strong> et <strong>Mac OS</strong>.<br />
Et Mono est loin d&#8217;être un jouet, il fonctionne réellement, je l&#8217;ai moi-même utilisé pour monter un serveur d&#8217;intégration continue <strong>Jenkins</strong> sur <strong>Ubuntu Server</strong>.<br />
Mono supporte la plupart des fonctionnalités du framework .Net mais un des rares composants manquant est WPF ; si je me souviens bien il a existé un projet d&#8217;implémentation nommé &#8220;Olive&#8221; mais il n&#8217;a jamais vraiment été démarré en raison de la quantité de travail que cela représente, notamment au niveau des couches basses de rendu.<br />
La seule technologie pour le développement d&#8217;interfaces graphiques implémentée par Mono est <strong>WinForms</strong> qui ironiquement grâce à cette portabilité pourrait survivre à WPF.</p>
<h2>Le syndrome Silverlight</h2>
<p>En tant qu&#8217;ex-développeur <strong>Silverlight</strong> j&#8217;ai appris à mes dépends que les technologies peuvent disparaitre beaucoup plus rapidement que prévu.<br />
Retour en 2008/2009 : <strong>RIA</strong> est un buzz-word, Microsoft fait la promotion de son propre framework, <strong>Silverlight</strong>, présenté lors des différents évènements Microsoft comme le futur, et tout logiquement les décideurs IT se mettent à l&#8217;intégrer à leurs écosystèmes.<br />
Donc de 2010 à début 2011 nous aussi commençâmes à développer des applications Silverlight.<br />
Mais très vite, dès 2011 donc, lors d&#8217;un évènement technique, à propos du web, étrangement Silverlight n&#8217;était plus sur le devant de la scène, et au contraire on nous faisait la promotion de l&#8217;écosystème <strong>HTML5</strong> (avec <strong>CSS</strong> et <strong>JS</strong>) en totale contradiction avec le discours des années précédentes.<br />
Officiellement toutefois rien n&#8217;avait changé pour Silverlight, mais étant un peu suspicieux, et malgré les propos officiels lénifiants, nous avons décidé d&#8217;arrêter les développements Silverlight, qui de toute façon n&#8217;avaient pas apportés les bénéfices escomptés (par exemple le déploiement n&#8217;étaient pas plug-and-play, et il fallait être administrateur pour installer le plugin Silverlight :/), pour nous concentrer sur WPF.<br />
Heureusement la majorité (peut être 85%) du code XAML et C# était partagée avec WPF, donc de ce côté peu fût perdu, et nous avons stoppé alors que nous n&#8217;étions pas encore complètement engagé.<br />
Ce fût la bonne décision car en 2013 la fin de Silverlight fût officiellement annoncée, et plus d&#8217;un responsable IT furent surpris par ce revirement car ils n&#8217;avaient pas vu les signes avant-coureurs.<br />
Je ne pense pas que cela sera aussi violent pour WPF, loin de là, mais quand vous avez vécu une telle déception vous arrêter de tout croire naïvement et devenez même méfiant, ce qui à mon avis est une qualité dans le contexte informatique actuel.</p>
<h1>Des raisons de ne pas paniquer</h1>
<p>A la lecture de la première partie de cet article vous avez peut être commencé à flipper, mais comme souvent les choses ne sont pas complètement noires, elles sont d&#8217;un gris plus ou moins foncé.<br />
La seconde partie va vous aider à diluer en grande partie ce noir avec du blanc, donc n&#8217;arrêter pas votre lecture ici&#8230;</p>
<h2>Toujours une équipe active</h2>
<p>Si l&#8217;on en croit <strong><em>Greg Levenhagen</em></strong> (<a href="http://greglevenhagen.com/is-wpf-dead-no/" title="Is WPF Dead? – NO!" target="_blank">Is WPF Dead? – NO!</a>) il y a toujours une équipe de développement activé dédiée à WPF.<br />
Greg ne fournit pas de chiffres donc il est difficile de mesurer l&#8217;effort de développement effectif.<br />
Bien qu&#8217;à mon avis il est évident que Microsoft n&#8217;abandonnera pas une technologie utilisée par des millions de personnes, y consacrer des développeurs dédiés, non mélangés à d&#8217;autres équipes, est une bonne chose.<br />
Et toujours selon Greg cette équipe ne serait pas seulement dédiée à la maintenance des versions existantes mais serait aussi en train d&#8217;en préparer une nouvelle (WPF 5?).<br />
Cependant sans prendre connaissance du change-log de cette version il est difficile d&#8217;être totalement optimiste : sans doute une version corrigeant des bugs et améliorant les performances, sans nouvelle fonctionnalité majeure.</p>
<h2>Toujours un effort de développement [MAJ 2014-11]</h2>
<p>En novembre 2014 l&#8217;équipe WPF a publié un article, <a href="http://blogs.msdn.com/b/dotnet/archive/2014/11/12/the-roadmap-for-wpf.aspx" title="The Roadmap for WPF" target="_blank">The Roadmap for WPF</a>, montrant que WPF était toujours activement développé.<br />
L&#8217;équipe travaille principalement sur des questions importantes comme les performances, qui ont été améliorées continuellement depuis les débuts de WPF, et les outils de debug complètement intégrés dans Visual Studio.<br />
Sans doute l&#8217;amélioration la plus importante est le support complet du tactile et des affichages haute-densité.<br />
Pourquoi est-ce si significatif ? Parce que ce sont des fonctionnalités des périphériques comme les tablettes et les téléphones mobiles, et WPF a été délaissé au profit de WinRT précisément parce que ce dernier avait été conçu spécialement pour ces périphériques.<br />
Ce n&#8217;est peut-être pas un revirement complet de la part de Microsoft en faveur de WPF, mais cela montre que Microsoft a entendu et pris en compte les demandes de la communauté.<br />
Pour plus d&#8217;informations regardez cette vidéo avec 2 des développeurs de WPF : <a href="http://channel9.msdn.com/Blogs/DevRadio/The-Future-of-WPF" title="The Future of WPF" target="_blank">The Future of WPF on Channel 9</a>.</p>
<h2>De nouvelles version des outils</h2>
<p>Du côté de l&#8217;outillage officiel on peut noter un signe positif : <a href="https://compositewpf.codeplex.com/" title="Prism CodePlex Home" target="_blank"><strong>Prism</strong></a>, un ensemble d&#8217;outils et de bonnes pratiques pour développer des applications XAML, a été mis à jour à la version 5, et au côté de la version dédiée à <strong>WinRT</strong> on trouve une nouvelle version pour <strong>WPF</strong>.</p>
<p>Comme indiqué dans la première partie le <strong>toolkit WPF officiel</strong> n&#8217;est plus développé, mais un autre projet a pris le relai : l&#8217;<a href="https://wpftoolkit.codeplex.com/" title="Extended WPF Toolkit Home" target="_blank"><strong>Extended WPF Toolkit</strong></a>.<br />
Il est fourni par un vendeur bien connu d&#8217;extensions, <a href="http://xceed.com/" title="Xceed Home" target="_blank"><strong>Xceed</strong></a>, donc par des experts WPF (et d&#8217;autres technologies Microsoft au passage), il est très riche fournissant notamment de nombreux composants additionnels, et surtout le projet est toujours activement développé, la dernière version actuellement (septembre 2014) datant de juin 2014, donc d&#8217;il y a moins de 3 mois.</p>
<p>Enfin, les deux <strong>frameworks MVVM</strong> de référence, <a href="https://mvvmlight.codeplex.com/" title="MVVM Light Toolkit CodePlex Home" target="_blank"><strong>MVVM Light Toolkit</strong></a> et <a href="https://caliburnmicro.codeplex.com/" title="Caliburn.Micro CodePlex Home" target="_blank"><strong>Caliburn.Micro</strong></a>, sont également actifs, les dernières versions ayant aussi moins de 3 mois.</p>
<p>Donc l&#8217;écosystème WPF est toujours bien vivant et même en évolution, ce qui est particulièrement rassurant pour les entreprises qui ainsi ne se retrouvent pas avec un tas de dépendances non maintenues.</p>
<h2>Des changements de management</h2>
<p>A la fin de 2012 <strong>Steven Sinofsky</strong>, alors <strong>Président de la Division Windows</strong>, quitta Microsoft.<br />
En quoi cela pourrait-il être un bon signe pour WPF ? Parce que Steven Sinofsky était connu pour sa haine de .Net et sa mauvaise volonté quand il s&#8217;agissait de travailler avec d&#8217;autres équipes (peut-être la raison première de son départ).<br />
C&#8217;est ce qui expliquerait partiellement, avec de véritables raisons techniques, pourquoi .Net ne fût pas utilisé comme pierre angulaire des nouvelles versions de Windows alors que c&#8217;est l&#8217;un des meilleurs outils logiciels jamais développé par Microsoft.<br />
Mais de l&#8217;extérieur il est difficile de distinguer la part de potins des véritables sentiments de Steven Sinofsky et leur impact effectif sur la conception de Windows 8+.</p>
<h2>L&#8217;inertie du marché des OS</h2>
<p>Un autre bon point pour WPF est le fait que <strong>les entreprises et les particuliers ne migrent pas immédiatement vers chaque nouvelle version de leur OS</strong>, et pour beaucoup de bonnes raisons : ça coûte de l&#8217;argent, ça prend du temps, c&#8217;est risqué, et c&#8217;est souvent tout simplement inutile.<br />
Changer d&#8217;OS est une tâche très lourde notamment en raison de la nécessité d&#8217;assurer la compatibilité des applications : celles fournies par des tiers comme Microsoft avec Office et celles développées par les équipes internes, et de mon expérience c&#8217;est un processus qui peut facilement prendre 2 ans.<br />
Actuellement (mi-2014) les parts de marché de WinRT sur le marché du PC sont plutôt réduites :<br />
&#8211; Windows 8 + 8.1 : ~15%<br />
&#8211; Windows 7 : ~55%<br />
&#8211; Windows Vista : ~5%<br />
&#8211; Windows XP : ~25%<br />
Donc sur plus de 80% des postes PCs il est impossible d&#8217;utiliser WinRT et le seul choix reste WPF.<br />
Et dans certains environnement c&#8217;est encore pire pour Windows 8+ : dans les entreprises que je connais dans le secteur financier la part de marché est simplement 0%, la migration vers Windows 7 n&#8217;étant même pas finie partout, certains continuant même à tourner sous XP notamment parce que le setup des applications de production n&#8217;est pas trivial.</p>
<p>En considérant que le cycle de renouvellement est d&#8217;environ 5 ans WPF devrait rester l&#8217;unique alternative pour de nombreuses entreprises d&#8217;ici la fin de la décennie.</p>
<h2>L&#8217;inertie de l&#8217;ALM</h2>
<p>Comme vous le savez probablement <strong>décommissionner les applications est coûteux</strong>: d&#8217;abord il faut organiser tout un tas de réunions et d&#8217;études préliminaires pour évaluer l&#8217;impact sur le métier, et vous devez souvent travailler dur pour convaincre certains utilisateurs qui vont quelquefois dégainer le joker du &#8220;risque opérationnel&#8221; ; puis il faut les remplacer par de nouvelles applications et s&#8217;assurer qu&#8217;il n&#8217;y a aucune régression, souvent en exécutant les deux versions côte à côte pendant une période tampon avant de complètement migrer ; de plus il faut éventuellement faire appel aux équipes BDD pour migrer les données, aux équipes réseau pour adapter les règles de firewalling&#8230;</p>
<p>C&#8217;est pourquoi les entreprises ne migrent leurs applications que quand il y a une véritable justification métier, et une toute nouvelle couche technique n&#8217;en est pas une, donc <strong>les applications WPF existantes</strong>, et il y en a énormément, <strong>sont là pour encore quelques temps</strong>, ce qui implique que les compétences WPF seront toujours nécessaires à court et moyen terme, et pour s&#8217;en convaincre il suffit de compter le nombre d&#8217;applications <strong>WinForms</strong> toujours en production, de nouvelles étant même créées chaque jour, et ce alors que WPF est sensé le remplacer depuis 2006.</p>
<p>De plus, d&#8217;un point de vue technique, bien que WPF et WinRT soient très similaires, il ne sont pas complètement compatibles : il y a toujours des fonctionnalités manquantes en WinRT 8.1 et des petites surprises : pour projeter un namespace vers XAML on utilise <code>clr-namespace</code> en WPF et <code>using</code> en WinRT, ce qui est suffisant pour casser la compatibilité du XAML et décourager toute velléité de sauter le pas !</p>
<h2>WPF est mature</h2>
<p>La réduction importante de l&#8217;effort de développement de WPF est évidente et peut être inquiétante, mais IMHO le développement ne fait que <strong>suivre un processus naturel</strong> que chaque développeur a déjà expérimenté : un gros effort de développement initial pour la première version, puis un effort toujours soutenu pour la version suivante qui bénéficie du feedback de la communauté, et finalement un effort minimal pour maintenir l&#8217;application.</p>
<p>C&#8217;est exactement le chemin suivi par WPF dont les premières versions (<strong>WPF 3.0</strong> (à mon avis en réalité une bêta) et <strong>3.5</strong>) qui apportèrent une nouvelle façon de développer des applications Windows, puis <strong>WPF 4</strong> apporta de nouveau composants majeurs venant du toolkit, comme la <code>DataGrid</code>, et améliora les performances, et finalement <strong>WPF 4.5</strong> introduisit seulement le Ribbon et continua à améliorer les performances.</p>
<p>Plus une technologie est mature moins elle nécessite un effort de développement important, et après 8 ans WPF est vraiment une technologie mature, donc les besoins de nouvelles fonctionnalité et de correction de bugs sont bien moindre.<br />
WPF est très probablement désormais entré dans la phase de maintenance de son cycle de vie donc il ne faut pas s&#8217;attendre à un développement frénétique.</p>
<h2>La niche du LOB</h2>
<p>S&#8217;il y a bien <strong>un domaine dans lequel WPF peut survivre et même continuer à briller c&#8217;est celui des applications LOB (Line Of Business)</strong>.<br />
Tout d&#8217;abord parce que l&#8217;expertise requise pour les développer repose en grande partie sur <strong>.Net</strong> qui est une plateforme mature que de nombreuses entreprises utilisent pour développer leurs applications LOB sur Windows, et elle ne vont pas faire une croix sur cette expertise, et bien au contraire essayer de la rentabiliser au maximum.</p>
<p>Certains <strong>outils .Net essentiels au développement LOB ne sont pas encore disponibles pour WinRT</strong>, comme les <strong>ORM</strong>s tels <strong>NHibernate</strong> ou <strong>Entity Framework</strong>, que la plupart des applications LOB utilisent pour accéder à leurs données relationnelles.</p>
<p>De plus pour certaines applications LOB importantes comme les plateformes de trading il n&#8217;y a aucun intérêt à utiliser WinRT parce qu&#8217;on n&#8217;a pas besoin de la mobilité et même parfois on ne la veut tout simplement pas pour des raisons de sécurité.<br />
Et ce type d&#8217;applications va même à l&#8217;encontre des directives officielles de Microsoft pour la conception des applications WinRT : elles devraient ne cibler que peu de fonctionnalités et n&#8217;afficher qu&#8217;un jeu de données minimal.</p>
<h2>L&#8217;intégration de Windows Forms</h2>
<p>Depuis plus de 10 ans les entreprises ont développé de nombreuses <strong>applications WinForms</strong>, et même les nouvelles applications utilisent souvent WinForms, malgré la disponibilité de son remplaçant WPF depuis 8 ans.<br />
Bien sûr les entreprises ne vont pas jeter toutes ces applications, composants et expertise juste pour utiliser de nouveaux jouets, elles veulent rentabiliser cet investissement au maximum.</p>
<p>Et à ma connaissance <strong>WinRT n&#8217;est pas encore capable d&#8217;intégrer des composants WinForms</strong>, donc WinRT n&#8217;est pas une option si vous voulez bénéficier de votre investissement WinForms.</p>
<p>Au contraire <strong>WPF a lui été conçu dès le départ pour permettre l&#8217;intégration avec WinForms</strong> : grâce au <strong><code>WindowsFormsHost</code></strong> il est possible d&#8217;embarquer des composants WinForms dans les applications WPF.<br />
Et mieux encore, <strong>on peut même intégrer des composants WPF dans les applications WinForms</strong> grâce à l&#8217;<strong><code>ElementHost</code></strong>.<br />
Tout cela permet de migrer en douceur vers WPF en évitant l&#8217;effet big-bang.</p>
<h2>La courbe d&#8217;apprentissage</h2>
<p>Si vous êtes un développeur WPF expérimenté sans le savoir <strong>vous êtes probablement déjà un développeur WinRT</strong> à environ 80%, et si vous êtes une entreprise <strong>vous possédez déjà 80% de l&#8217;expertise nécessaire au développement d&#8217;applications WinRT</strong>.<br />
En effet la plupart des outils fondamentaux pour développer des applications WPF sont les mêmes en WinRT :<br />
&#8211; mêmes langages procéduraux : C#, VB.Net&#8230;<br />
&#8211; même langage de balisage : XAML,<br />
&#8211; même façon de connecter vue et données : liaison de données, DataTemplates&#8230;<br />
&#8211; architecture applicative similaire : structuration générale, ressources&#8230;<br />
&#8211; mêmes design-patterns et implémentations : MVVM, INotifyPropertyChanged, INotifyCollectionChanged, ICommand&#8230;<br />
Donc tout investissement dans d&#8217;autres plateformes XAML comme WPF et Silverlight peut être en grande partie rentabilisé pour WinRT, réduisant ainsi la pente de la courbe d&#8217;apprentissage (vous souvenez-vous de celle de WPF quand vous étiez débutant ? ;))</p>
<h2>WPF est riche</h2>
<p>WinRT n&#8217;est pas un clone de WPF et certaines fonctionnalités n&#8217;y sont pas encore implémentées, donc si vous développez des applications seulement pour les clients lourds alors d&#8217;un point de vue technique WPF a toujours le dessus.<br />
Cependant, et c&#8217;est pourquoi j&#8217;en parle en dernier, pour de nombreuses applications cet écart n&#8217;est pas rédhibitoire, et à mesure que WinRT évoluera il se réduira d&#8217;autant, mais il est probable que même à long terme certains développements avec des besoins très spécifiques ne puissent être faits qu&#8217;avec WPF.</p>
<p>Mais il faut bien garder en tête que la valeur ajoutée de WinRT n&#8217;est pas dans sa richesse technique intrinsèque mais plutôt dans son modèle de développement qui donne accès aux <strong>plateformes mobiles</strong> et au <strong>Windows store</strong>.</p>
<h1>Stratégie pour le futur</h1>
<p>Que vous soyez une entreprise ou un développeur individuel vous devriez sérieusement penser à ralentir votre investissement dans WPF, et commencer à monter en compétence sur WinRT.</p>
<h2>Pour les entreprises</h2>
<p>En tant qu&#8217;entreprise vous ne pouvez arrêter vos développements WPF tant que vous devez supporter d&#8217;anciennes versions de Windows, y compris Windows 7.<br />
Concernant vos applications existantes il n&#8217;y a pas d&#8217;inquiétude à avoir, il n&#8217;est pas nécessaire de les migrer vers WinRT, sauf si vous souhaitez bénéficier de ses nouvelles capacité de déploiement via le Windows Store.<br />
En effet Microsoft devrait continuer à assurer le support de WPF pour les années à venir ; la rétrocompatibilité est quelque chose que Microsoft prend très au sérieux.<br />
Par exemple bien qu&#8217;il soit plus difficile de mettre en place un environnement VB6 dans les nouvelles versions de Windows cela reste possible, et une fois installées les applications continuent à s&#8217;exécuter sans problème.</p>
<p>Selon votre main d&#8217;oeuvre IT, vous devriez consacrer un peu de temps à la veille technique et avoir des développeurs qui commencent sérieusement à étudier WinRT : comment votre entreprise pourrait en profiter, typiquement en élargissant son audience, comment les nouvelles applications devraient être développées, comment les outils et codes existants peuvent-ils être réutilisés, quels sont les obstacles éventuels à anticiper&#8230;<br />
Pour les applications qui pourraient bénéficier de WinRT pour le mobile et les tablettes vous pouvez commencer à élaborer des plans de migration, ce qui n&#8217;est pas évident car WinRT ne possède pas encore de nombreuses fonctionnalités de WPF sur lesquelles vos applications pourraient reposer.<br />
Commencez à développer des applications prototypes pour valider la nouvelle technologie dans votre environnement particulier et voyez par vous même si cela apporte un quelconque bénéfice.</p>
<h2>Pour les développeurs</h2>
<p>Nous autres développeurs ne souhaitons pas investir dans des compétences techniques dont personne n&#8217;a besoin, et nous essayons souvent de nous construire un portefeuille de connaissances assez large afin de répondre aux besoins du plus grand nombre d&#8217;entreprises et de projets possibles, afin de réduire le risque d&#8217;être laissé au bord de la route.<br />
Donc si vous êtes un développeur WPF expérimenté et que vous hésitez entre renforcer et étendre votre savoir-faire WPF pour devenir un expert, et commencer à monter en compétence sur WinRT, je vous conseille plutôt la seconde option.<br />
Bien sûr vous aurez sans doute l&#8217;opportunité de faire les deux comme j&#8217;essaye, mais WinRT devrait être quelque part sur votre TODO-list sans toutefois être une priorité.</p>
<p>Ou bien encore vous pourriez continuer à investir dans WPF dans l&#8217;attente que le marché soit en manque de développeurs WPF, comme c&#8217;est le cas avec d&#8217;anciennes technologies comme COBOL et VB6, mais j&#8217;ai bien peur qu&#8217;il vous faille attendre une bonne décennie avant que cela n&#8217;arrive, car avec la croissance importante de l&#8217;IT au sein des entreprises, pour quasiment toute les technologies on trouve de nombreux développeurs sur le marché, et c&#8217;est particulièrement vrai pour les technologies mainstreams comme WPF, donc je ne compterais pas trop dessus.</p>
<p>Ne soyez pas abattu ou fâché par cette nième toute nouvelle technologie, c&#8217;est le business-model de notre secteur : il a besoin de créer de nouveaux produits à vendre à ses clients tout le temps (rappelez-vous le SOA qui déversa énormément d&#8217;argent directement dans les poches des entreprises informatiques, de leurs employés, de leurs actionnaires et des développeurs), de la même façon qu&#8217;Apple le fait avec ses iPhone 1, 2, 3, &#8230; maintenant 6 et bientôt 42.<br />
C&#8217;est comme ça que ça fonctionne et nous avons la chance, en tant que développeurs, d&#8217;être du bon côté de la barrière, en faisant de cette entropie notre gagne pain, et en toute objectivité la plupart de ces technologies améliore la vie des entreprises et des particuliers.</p>
<h1>Conclusion</h1>
<p>Je pense que la somme de tous ces faits est plutôt claire : <strong>WPF est le passé et le présent</strong>, dans le future proche il sera en concurrence direct avec WinRT, mais plus tard quand Windows 8+ aura acquis plus de parts de marché alors <strong>WPF deviendra plus ou moins obsolète comme le sont aujourd&#8217;hui, à des degrés divers, d&#8217;anciennes technologies Microsoft telles que VB6 ou WinForms</strong>.</p>
<p>Surtout il ne faut pas tomber dans le déni, et rester lucide sur les changements en cours, et ne pas ignorer les faits pessimistes de son esprit.<br />
Il ne faut pas espérer une renaissance de WPF, il n&#8217;existe rien te tel en informatique (bon il est vrai que COM est plus ou moins de retour avec WinRT), WPF n&#8217;est de toute évidence pas taillé pour les nouvelles tendances, les nouveaux outils comme WinRT le sont.</p>
<p>Bien sûr tout n&#8217;est pas sombre: <strong>WPF n&#8217;est ni mort et obsolète ni mourant et obsolescent</strong>, il a juste atteint son apogée et risque de doucement disparaître à mesure que les entreprises migrent leur infrastructure vers Windows 8+ leur permettant de choisir WinRT pour leurs futurs développements.</p>
<p><strong>Soyez pragmatique et transparent</strong>: utilisez WPF tant qu&#8217;il apporte de la valeur à vos clients et portez ces faits à leur connaissance, et aidez les à préparer l&#8217;avenir.<br />
J&#8217;ai moi même commencé à mettre à jour mes supports de formation en y intégrant des morceaux de WinRT, et en ajoutant une page résumant ces faits, les mettant en évidence selon leur importance.</p>
<p><strong>Cependant IMHO vous ne devriez pas non plus trop investir dans WinRT.</strong><br />
Pourquoi ? Parce que plus je joue avec WinRT et y réfléchis moins je le trouve pertinent :</p>
<ul>
<li>si vous développez une application LOB, votre seule plateforme cible est sans doute le PC Windows, et vous avez besoin d&#8217;être rétro-compatible avec les &#8220;anciennes&#8221; versions de Windows, au moins Windows 7, donc WinRT n&#8217;est clairement pas une option et vous devez utiliser WPF,</li>
<li>si vous souhaitez cibler les tablettes et les téléphones vous ne pouvez faire l&#8217;impasse sur 90% du marché, iOS et Android, donc WinRT n&#8217;est pas une option, et vous devez utiliser soit la stack web (JavaScript/HTML/CSS) soit des frameworks natifs cross-plateformes comme Xamarin (C#) ou QT (C++).</li>
</ul>
<p>Donc pour la plupart des cas d&#8217;utilisation WinRT n&#8217;est tout simplement pas une option.</p>
<p>De plus notez que Microsoft investit lourdement dans les technologies sus-citées.</p>
<p>Il est sans doute trop tôt pour vous demandez &#8220;<strong><em>Est-ce la fin de WinRT (en tant que plateforme de développement finale) ?</em></strong>&#8221; mais je serais relativement surpris si WinRT arrivait à décoller et à devenir une plateforme de développement majeure.</p>
<p>IMHO WinRT est une bonne plateforme seulement pour les équipes Microsoft qui peuvent ainsi partager plus de code entre les différentes versions de l&#8217;OS Windows, imitant l&#8217;effort d&#8217;Apple ; mais pour le développeur final les cas d&#8217;utilisation de WinRT sont bien trop limités : partager du code entre PC, tablettes et téléphones mais seulement pour les périphériques Windows.<br />
Sans doute que certaines entreprises n&#8217;ont que ce besoin mais je doute qu&#8217;elles soient nombreuses car désormais les application sont souvent utilisées depuis les appareils personnels des employés (BYOD) qui peuvent être n&#8217;importe quoi et le plus souvent de l&#8217;iOS ou de l&#8217;Android.</p>
]]></content:encoded>
							<wfw:commentRss>http://pragmateek.com/french-est-ce-la-fin-de-wpf-present-et-futur-de-wpf/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
							</item>
		<item>
		<title>Is WPF dead: the present and future of WPF</title>
		<link>http://pragmateek.com/is-wpf-dead-the-present-and-future-of-wpf/</link>
				<comments>http://pragmateek.com/is-wpf-dead-the-present-and-future-of-wpf/#comments</comments>
				<pubDate>Fri, 12 Sep 2014 17:35:43 +0000</pubDate>
		<dc:creator><![CDATA[pragmateek]]></dc:creator>
				<category><![CDATA[.Net Development]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[WPF]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[API]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[certification]]></category>
		<category><![CDATA[mobile]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[pattern]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[winrt]]></category>
		<category><![CDATA[XAML]]></category>

		<guid isPermaLink="false">http://pragmateek.com/?p=3265</guid>
				<description><![CDATA[Introduction As a WPF developer for years I was recently concerned by the new direction chosen by Microsoft on its client platforms with the rise of the brand new WinRT framework. I was concerned for good reasons: I&#8217;ve suffered from &#8230; <a href="http://pragmateek.com/is-wpf-dead-the-present-and-future-of-wpf/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
								<content:encoded><![CDATA[<p></p>
<h1>Introduction</h1>
<p>As a <strong>WPF</strong> developer for years I was recently concerned by the new direction chosen by Microsoft on its <strong>client platforms</strong> with the rise of the brand new <strong>WinRT</strong> framework.</p>
<p>I was concerned for good reasons: I&#8217;ve suffered from the collateral damages of the <strong>Silverlight</strong> failure, and as the proverb says &#8220;once bitten, twice shy&#8221;.<br />
Since 2009 I have put a huge personal and professional investment in WPF, using it to develop <strong>LOB applications</strong> in the financial industry, and now I&#8217;m even providing training on this topic.<br />
So as a professional developer and trainer the future of WPF is critical for me so I&#8217;ve studied this issue more thoroughly.</p>
<p>In this article I&#8217;ll share my findings with you, in a completely objective and transparent manner, and I hope you&#8217;ll provide your own facts, so that the community can have a better vision of the future of WPF.<br />
In the last part of this article I provide some strategies for businesses and individual developers.</p>
<p><span id="more-3265"></span></p>
<h1>Some reasons to worry</h1>
<p>First I&#8217;ll start by presenting the signs that are worrying me, and should worry you too if you are a WPF stakeholder.</p>
<h2>WPF team&#8217;s blog is idle</h2>
<p>As every Microsoft technical team the WPF development team owns a <a href="http://blogs.msdn.com/b/wpf/" title="WPF Team's Blog" target="_blank"><strong>blog</strong></a> where the team&#8217;s members share their expertise on WPF with the community.<br />
The last article of this blog is dated from may 2011 so <strong>more than 3 years ago</strong>, precisely when <strong>WinRT</strong> was starting to emerge as the next big thing.<br />
An idle blog could mean a lot of things but IMHO nothing good: probably the team was reduced to the bare minimum and animating this blog is not a priority, maybe the best members of the team have been moved to other projects like WinRT, and maybe this is intentional to send a signal to the community&#8230;<br />
In terms of public relations an active blog is essential because it shows the technology is evolving and is developed by enthusiast developers proud of their work and willing to share it with the community.<br />
Note that often the MSDN blogs are not very active, the Entity Framework team&#8217;s blog being one of the exceptions, thanks to Rowan Miller who regularly publishes new posts, and this is one of the main reason I like this technology: it is being developed by brilliant and committed people.</p>
<h2>The official WPF toolkit is idle</h2>
<p>The <a href="https://wpf.codeplex.com/" title="WPF Toolkit Home" target="_blank"><strong>WPF Toolkit</strong></a> is a free and open source project developped by the Microsoft team and designed as the anteroom of the official WPF releases.<br />
As an example the <strong><code>DataGrid</code></strong> was not present in the initial release (WPF 3.0 and 3.5) but was available in the toolkit, and was finally added to WPF 4.0.<br />
The official toolkit played this role till 2010, but since then the project is idle, so seems like there is no more stuff in stock for a next release.<br />
Sign of this inactivity: for the &#8220;WPF Toolkit&#8221; search Google ranks the official WPF toolkit second after a non official one (more on this one in the second part).</p>
<h2>No more certification</h2>
<p>The official <strong>WPF certification</strong> (<strong>70-511</strong>) will not be continued and it will <strong>expire at summer 2015</strong>.<br />
This is a strong explicit sign given to developers that they should not invest more time in this technology and instead devote their time to WinRT which benefits from new dedicated certification paths.<br />
Maybe Microsoft will step back and postpone this removal like it did with other certifications after the developers community complained, but that won&#8217;t change the fact WPF is no more the priority.<br />
Personally I&#8217;m still hesitating to pass it because I have no guarantee the time and money (yes as an entrepreneur I pay my certifications myself) are worth it.<br />
Instead I prefer to prepare for the WinRT certifications which should be there for some years.</p>
<h2>No Windows 8+ integration</h2>
<p>If you remember the release of <strong>WPF 4</strong>, a large part of the enhancements were dedicated to <strong>Windows 7 integration</strong> like taskbar items customization (jump-lists, progress, overlay&#8230;).<br />
There is no such things in <strong>WPF 4.5</strong> to allow full integration to <strong>Windows 8+</strong> features like the charm bar and the numerous application contracts though there is some interop capabilities.<br />
So if Microsoft has not invested in this integration it clearly demonstrates that WPF is no more a first-class citizen in Windows and it prefers to dedicate all its workforce to WinRT, and I think this is a reasonable decision.</p>
<h2>No support for Windows RT</h2>
<p>Microsoft, historically a <strong>softwares vendor</strong>, is diversifying its business by becoming an <strong>hardware vendor</strong>, mimicking its competitors Apple and Samsung.<br />
To this end Microsoft has acquired <strong>Nokia</strong> to benefit from its long time presence in the <strong>mobile phone market</strong>.<br />
On the <strong>tablets</strong> and <strong>laptops</strong> side, to compete with <strong>iPad</strong> tablets and <strong>MacBook Pros</strong> laptops, Microsoft has launched the <strong>Surface</strong> series.<br />
There were 2 versions of the <strong>Surface 1</strong> and <strong>2</strong> depending on the hardware architecture: <strong>x86</strong> and <strong>ARM</strong>, the later benefiting from a dedicated version of Windows: <strong>Windows RT</strong> (not to be confused with WinRT which is a software layer).<br />
But Windows RT does not support (at least officially) the older APIs like the good old <strong>Win32</strong>, hence does not support all the &#8220;wrappers&#8221; like <strong>WinForms</strong> and &#8230; <strong>WPF</strong>, so you can&#8217;t run your WPF applications on all the Surface versions.<br />
And if Microsoft did not invest in this it&#8217;s simply because it tries to get rid of Win32 to replace it with WinRT which is specially tailored for the new IT trends.</p>
<h2>The new Microsoft&#8217;s strategy</h2>
<p>In february 2014 Microsoft named a new <strong>CEO</strong>, <strong>Satya Nadella</strong>, who comes from the <strong>cloud division</strong> of Microsoft.<br />
He is replacing Steve Ballmer, who did not understood the new mobile market (first <a href="https://www.youtube.com/watch?v=eywi0h_Y5_U" title="Ballmer on iPhone" target="_blank"><strong>iPhone</strong></a> and <a href="https://www.youtube.com/watch?v=MTX1e-pMN6E" title="Ballmer on Android" target="_blank"><strong>Android</strong></a>) and is probably one of the reasons Microsoft completely missed the boat and is now fighting hard to get a place taking market shares to competitors (Apple, Samsung) percent after percent.<br />
Contrary to his predecessor Satya Nadella&#8217;s global strategy for Microsoft is &#8220;<strong>cloud first and mobile first</strong>&#8220;, so exit the traditional desktop model, and again this is a very sane strategy.<br />
But precisely WPF was designed for the &#8220;old&#8221; model: fat desktop applications, whereas WinRT uses a totally different model, taking into account the new mobile needs.<br />
Of course the desktop and PC market is not dead, far from it, but it is not the predominant model anymore.<br />
And Microsoft has taken this into account when building WinRT because you can now use the whole HTML/CSS/JS stack, including frameworks like Angular and Knockout, to develop desktop applications; a strong sign confirming that web technologies are really becoming ubiquitous (after Node on the server).</p>
<h2>The Windows Store</h2>
<p>In order to capture a part of the applications vendors revenues most of the platforms&#8217; owners like <strong>Apple</strong> and <strong>Microsoft</strong> have created &#8220;<strong>stores</strong>&#8221; you must use to publish and buy applications.<br />
And unfortunately AFAIK the Windows Store applications must be based on WinRT, so your WPF applications can&#8217;t be deployed through the store.<br />
Note that this is not an issue for businesses that deploy their applications internally and don&#8217;t need a store, nor for big applications vendors like ERP who use their own commercial channels to sell their applications, but this is an issue if you are a small vendor who need the visibility of the store, before a competitor eats your market shares.<br />
More and more people are using the stores instinctively to search for new applications so there is almost no way around them.<br />
So if you intend to develop your brand new application in WPF you will have a hard time distributing it and even harder if you intend to sell it, so you should instead use WinRT.</p>
<h2>Mobility</h2>
<p>You probably consume a big part of your daily content through your <strong>mobile phone</strong> using web or native applications so you understand how important it is nowadays to be present on this market: you must provide a mobile version of your applications.<br />
WPF has never been a platform for mobile development and is not a player in this market, and for years the answer was <strong>Silverlight for Windows Phone</strong> and it was the reference toolkit up to Windows Phone 7.<br />
But using one toolkit per platform was not ideal, even though you could share most of the procedural and markup code.<br />
WinRT is an answer to this issue because it is a common toolkit designed to ease development on all the Windows platforms which are more and more unified at the OS level with Windows 8+.</p>
<p>Note that for a really cross-platform development that also targets <strong>Android</strong> et <strong>iOS</strong> Microsoft does not provide any tool, so you have to turn to <a href="http://xamarin.com/" title="Xamarin" target="_blank"><strong>Xamarin</strong></a> which is a really promising project.</p>
<h2>Costs of maintenance</h2>
<p>If you&#8217;ve worked with Microsoft technologies for years you know that Microsoft spends its money sparingly, and for good reasons: first, as a company, it must make money to survive and nowadays shareholders ask more, so a penny is a penny, second implementing even a small feature is costly because there is a lot of steps involved; Eric Lippert gives an overview in this blog post: <a href="http://blogs.msdn.com/b/ericlippert/archive/2003/10/28/53298.aspx" title="How many Microsoft employees does it take to change a lightbulb?" target="_blank">How many Microsoft employees does it take to change a lightbulb?</a>.<br />
So when the community asks for a bug fix or a new feature, it is implemented only if it&#8217;s really a big one:<br />
&#8211; either critical like security breaches, so even a few numbers of impacted users will trigger the implementation<br />
&#8211; or minor but annoying a lot of people<br />
Developing both WPF and WinRT would imply answering to both toolkits&#8217; feature requests and fixing both toolkits&#8217; bugs, this is clearly not an option, especially as Microsoft is currently reducing its workforce.</p>
<h2>Portability</h2>
<p>What could have &#8220;saved&#8221; WPF would be some <strong>niches</strong>, e.g. as a <strong>portable technology</strong> to develop client applications, but unfortunately this is not the case.<br />
There is a <strong>portable version of .Net</strong> (to be pedantic, of the <strong>CLI</strong>): <strong>Mono</strong>, which runs on <strong>Windows</strong> of course but also on <strong>Linux</strong>, <strong>Unix</strong> and <strong>Mac</strong>.<br />
And Mono is not a toy technology, it really works, with it I&#8217;ve myself already built a <strong>Jenkins</strong> integration server on <strong>Ubuntu Server</strong>.<br />
Mono supports most of the .Net framework stack but one of the few missing parts is WPF; if I remember well there was a project named &#8220;Olive&#8221; to implement it but it was never really started due to the huge work it represents, especially at the low level rendering layers.<br />
The only UI technology Mono has implemented is <strong>WinForms</strong>, so ironically WinForms could survive WPF thanks to its portability.</p>
<h2>The Silverlight syndrome</h2>
<p>I once was a <strong>Silverlight</strong> developer and I&#8217;ve discovered that technologies can vanish quicker than I once expected.<br />
Back in 2008/2009: <strong>RIA</strong> is a buzz word, Microsoft is branding its own framework, Silverlight, in businesses managers see it in Microsoft events and want it in their IT ecosystem.<br />
So in 2010 and first quarter of 2011 we started developing Silverlight applications.<br />
But somewhere in 2011 at one of the technical events, concerning the web, Microsoft stopped putting Silverlight in the spotlight, and instead started promoting the HTML5 ecosystem (with CSS and JS).<br />
Officially the story had not changed for Silverlight, but I was quite suspicious, reported it, and our team decided to stop Silverlight developments, which by the way had not delivered the expected benefits (e.g. Silverlight was not plug-and-play because you needed to be administrator to install the Silverlight player :/), to instead concentrate on &#8220;traditional&#8221; WPF.<br />
Hopefully most (maybe 85%) of the XAML and C# code was shared with WPF, so not too much was really lost, and we stopped while we were not too much committed.<br />
And this was the right choice because in 2013 the death of Silverlight was officially announced, and more than one IT stakeholder were surprised because they had not seen the forewarning signs.<br />
I don&#8217;t think things will be that violent for WPF, but when you&#8217;ve lived such a disappointment you stop being naive and tend to become distrustful, which in my opinion is a quality in the current IT context.</p>
<h1>Some reasons not to panic</h1>
<p>After reading the first part you may be starting to freak out but as often things are not completely black, they are gray, a more or less dark gray.<br />
This second part will help you mix the white with the black, so keep reading&#8230;</p>
<h2>Still an active team</h2>
<p>According to <strong><em>Greg Levenhagen</em></strong> (<a href="http://greglevenhagen.com/is-wpf-dead-no/" title="Is WPF Dead? – NO!" target="_blank">Is WPF Dead? – NO!</a>) there is still an active development team dedicated to WPF.<br />
Greg does not provide any hard numbers so it&#8217;s hard to measure the development effort.<br />
While it&#8217;s obvious Microsoft wouldn&#8217;t  abandon a technology used by millions of people, having dedicated developers, not merged in other teams, is a good thing.<br />
And still according to Greg this team is not only dedicated to maintenance of existing versions but is also preparing at least a next release (WPF 5?).<br />
Without having the change-log of this version it&#8217;s hard to be too optimistic: probably this will be only a bug-fixes and performance enhancement version without any major features.</p>
<h2>Still a development effort [Update 2014-11]</h2>
<p>In november 2014 the WPF team published an article, <a href="http://blogs.msdn.com/b/dotnet/archive/2014/11/12/the-roadmap-for-wpf.aspx" title="The Roadmap for WPF" target="_blank">The Roadmap for WPF</a>, showing that WPF was still actively developed.<br />
The team is mainly working on important issues like performances, which have been continuously enhanced since the inception of WPF, and tooling fully integrated into Visual Studio.<br />
Maybe the more important enhancement is the full support of touch and high-density display.<br />
Why is it so significant ? Because these are features of devices like tablets and phones, and WPF was dropped in favor of WinRT precisely because the later has been specifically designed for such devices.<br />
This may not be a complete u-turn from Microsoft in favor of WPF but it shows that Microsoft has heard and taken into account the claims of the community.<br />
For more information check this nice video with two of the WPF developers: <a href="http://channel9.msdn.com/Blogs/DevRadio/The-Future-of-WPF" title="The Future of WPF" target="_blank">The Future of WPF on Channel 9</a>.</p>
<h2>New tools versions</h2>
<p>I&#8217;ve noticed a positive sign on the official tooling side of things: <a href="https://compositewpf.codeplex.com/" title="Prism CodePlex Home" target="_blank"><strong>Prism</strong></a>, a set of tools and best practices for developing XAML applications, has been updated to version 5 and along with the <strong>WinRT</strong> version it does provide a new version for <strong>WPF</strong>.</p>
<p>As said in the first part, the <strong>official WPF toolkit</strong> is idle but another project picked up the torch: the <a href="https://wpftoolkit.codeplex.com/" title="Extended WPF Toolkit Home" target="_blank"><strong>Extended WPF Toolkit</strong></a>.<br />
It is being developed by a well known extensions&#8217; vendor, <a href="http://xceed.com/" title="Xceed Home" target="_blank"><strong>Xceed</strong></a>, so by WPF experts (and other Windows technologies by the way), and it is very rich with a bunch of additional controls, and most importantly the project is actively developed, latest version being from june 2014, so less than 3 months ago as of this writing.</p>
<p>Finally the two top <strong>MVVM frameworks</strong>, <a href="https://mvvmlight.codeplex.com/" title="MVVM Light Toolkit CodePlex Home" target="_blank"><strong>MVVM Light Toolkit</strong></a> and <a href="https://caliburnmicro.codeplex.com/" title="Caliburn.Micro CodePlex Home" target="_blank"><strong>Caliburn.Micro</strong></a>, are active, new versions are 3 months old.</p>
<p>So the WPF tools ecosystem is still living and evolving which is especially reassuring for businesses because they are not left with a bunch of unmaintained projects.</p>
<h2>Change in management</h2>
<p>At the end of 2012 <strong>Steven Sinofsky</strong>, at this time <strong>President of the Windows Division</strong>, left Microsoft.<br />
Why would it be a positive sign for WPF? Because Steven Sinofsky was famed for being a .Net hater and not playing well with the other teams (maybe the primary reason of his departure).<br />
And this would partially explain, along with some real technical reasons, why .Net was not used as the foundation block of the next Windows versions whereas it is one of the best piece of software ever made by Microsoft.<br />
From the outside it&#8217;s hard to evaluate the part of gossip and the real feelings of Steven Sinofsky and their impact on the design decisions for Windows 8+.</p>
<h2>The OS market inertia</h2>
<p>Another good point for WPF is the fact <strong>businesses and individuals don&#8217;t migrate immediately to each brand new OS version</strong>, and for a lot of good reasons: it costs money, it takes some time, it&#8217;s risky, and often it&#8217;s simply useless.<br />
Migrating to a new OS is a really daunting task due to the need of ensuring compatibility of the applications: those provided by an external vendor like Microsoft with Office and those developed by the internal teams, and from my experience it&#8217;s a process that can easily take 2 years.<br />
Currently (mid-2014) the market shares of WinRT on the PC market are quite reduced:<br />
&#8211; Windows 8 + 8.1 : ~15%<br />
&#8211; Windows 7 : ~55%<br />
&#8211; Windows Vista : ~5%<br />
&#8211; Windows XP : ~25%<br />
So for more than 80% of PCs you can&#8217;t use WinRT and have no other choice than WPF.<br />
And in some context this is worst for Windows 8+: in the companies I know in the financial sector in France this is simply 0%, the migration to Windows 7 is not even completed everywhere, and I know some still running with Windows XP because setup of applications is not trivial.<br />
Considering the renewal cycle is about 5 years WPF should be the unique choice for a lot of businesses till the end of the decades.</p>
<h2>The ALM inertia</h2>
<p>As you probably know <strong>retiring applications is costly</strong>: first you have preliminary studies with a bunch of meetings to assess the impact it will have on the business, and you have to work hard to convince some users who will sometimes put the &#8220;operational risk&#8221; joker on the table; then you have to replace them with brand new application and you must ensure there is no regression, often running both the old and new versions side by side during a certain period of time before completely switching; moreover you may have to call up your DB teams to migrate the data, the network teams to adapt the firewall rules&#8230;<br />
It&#8217;s why businesses migrate applications only when there is a valid business reason, and a brand new technical layer is not one, so <strong>the existing WPF applications</strong>, and there is a bunch, <strong>are here to stay</strong>, and it means WPF skills will be needed in the foreseeable future, just have a look at the number of <strong>WinForms</strong> applications still in the wild, and new ones are being developed every day, whereas WPF is available to replace it since 2006.<br />
And from a technical point of view, while WPF and WinRT are really similar, they are not fully compatible: there are still missing features in WinRT 8.1 and some quirks: to map a namespace to XAML you use <code>clr-namespace</code> in WPF and <code>using</code> in WinRT, this is enough to break XAML compatibility and discourage any flimsy will to jump!</p>
<h2>WPF is mature</h2>
<p>The obvious important decrease of the development effort for WPF can be worrying but IMHO it is only <strong>following a natural path</strong> every developer has experimented: a huge effort to develop the first release, then still a sustained effort for the following release that benefits from the feedback of the community, and finally a minimal effort to maintain the application.<br />
This is exactly the path followed by WPF with a first versions (<strong>WPF 3.0</strong> (for me was more of a beta version) and <strong>3.5</strong>) bringing a new way of developing Windows applications, then <strong>WPF 4</strong> introduced some new controls moved from the toolkit, like the <code>DataGrid</code>, and performance enhancements, and finally <strong>WPF 4.5</strong> introduced the Ribbon and still some performance enhancements.<br />
So the more mature a technology is the less development effort it needs, and after 8 years WPF is a really mature technology, so the needs for new features and bug fixes are reduced.<br />
And probably WPF has now entered the maintenance phase of its life-cycle so don&#8217;t expect frenetic development of it.</p>
<h2>The LOB niche</h2>
<p>If there is <strong>a domain where WPF can survive and even continue to shine this is LOB (Line Of Business) applications</strong>.<br />
First because most of the expertise to develop them is based on <strong>.Net</strong> which is a mature platform that a lot of companies running Windows use to develop their LOB applications and won&#8217;t throw away but instead leverage as much as they can.<br />
And some central <strong>.Net tools are not yet available for WinRT</strong>, e.g. <strong>ORM</strong>s like <strong>NHibernate</strong> or <strong>Entity Framework</strong>, which are necessary to most LOB applications to access their relational data.<br />
Second for some big LOB applications like trading platforms there is no benefit to use WinRT because you don&#8217;t need and even don&#8217;t want, for security reasons, mobility.<br />
And this kind of big applications even go against the official guidelines of Microsoft for designing WinRT applications: they should be focused with a minimal set of data on the screen.</p>
<h2>Windows Forms integration</h2>
<p>For more than 10 years a lot of businesses have created many <strong>WinForms applications</strong>, and new applications are still being developed with WinForms, despite WPF being there for 8 years as its replacement.<br />
Of course businesses don&#8217;t want to throw away all these applications, components and expertise just to use new toys, they want to leverage their investment as much as possible.<br />
And AFAIK <strong>WinRT is not yet able to integrate WinForms components</strong>, so using WinRT is not an option if you want to profit from your WinForms investment.<br />
On the contrary <strong>WPF has been designed from the start to allow integration of WinForms</strong>: using the <strong><code>WindowsFormsHost</code></strong> you can embed WinForms components inside your WPF applications.<br />
And better, <strong>you can even integrate WPF components inside a WinForms application</strong> using the <strong><code>ElementHost</code></strong>, so that you can migrate slowly to WPF avoiding the big-bang effect.</p>
<h2>The learning curve</h2>
<p>If you are a seasoned WPF developer without knowing it <strong>you are probably already a WinRT developers</strong> at say 80%, and if you are a business <strong>you already have 80% of the expertise to develop WinRT applications in stock</strong>.<br />
The reason is that most of the fundamentals tools for developing WPF applications are the same for WinRT:<br />
&#8211; same procedural languages: C#, VB.Net&#8230;<br />
&#8211; same markup language: XAML,<br />
&#8211; same way to link view to data: data binding, DataTemplates&#8230;<br />
&#8211; similar architecture of applications: global structuring, resources&#8230;<br />
&#8211; same design patterns and implementations: MVVM, INotifyPropertyChanged, INotifyCollectionChanged, ICommand&#8230;<br />
So most of your investment in other XAML platforms like WPF and Silverlight can be leveraged for WinRT, reducing the steepness of the learning curve (remember the one of WPF when you were a newbie? ;))</p>
<h2>WPF is rich</h2>
<p>WinRT is not a clone of WPF and some features are not yet implemented, so if you are only developing desktop applications from a technical capabilities point of view WPF is still better.<br />
But I put it as the last one because IMHO it is not really significant, and as WinRT will continue its evolution the gap will become smaller and smaller, but I guess some developers with really specific needs won&#8217;t be able to develop with WinRT and will need WPF.<br />
But again the added value of WinRT is not in its intrinsic technical richness but more in the development model it offers with access to mobile platforms and the <strong>Windows store</strong>.</p>
<h1>Strategy for the future</h1>
<p>Whether you are a business or an individual developer you should seriously consider slowing down your technical investment in WPF, and start to build your expertise on WinRT.</p>
<h2>Businesses</h2>
<p>As a business you can&#8217;t stop your WPF developments as long as you have some older versions of Windows, including Windows 7.<br />
As for your existing applications, don&#8217;t worry, you don&#8217;t need to migrate them to WinRT, unless you want to benefit from its new capabilities as deployment through the Windows store.<br />
Indeed Microsoft should ensure support for WPF for the foreseeable future; backward compatibility is something Microsoft takes really seriously.<br />
As an example while it may be harder to setup VB6 environments in new versions of Windows it is still possible and, hence setup, your applications should continue to work seamlessly.</p>
<p>Depending on your available IT workforce, you should devote time to technology intelligence and have some developers starting to think about WinRT: how you could benefit from it, typically to broaden your audience, how new applications should be developed, how the existing tools and code can be reused, what are the potential issues to anticipate&#8230;<br />
For the applications that could benefit from WinRT for mobile and tablet you can start building some migration path, which is not that obvious because WinRT is missing many features from WPF.<br />
Start to develop proof-of-concept applications to validate the new technology in your particular context and see for yourself if it delivers.</p>
<h2>Developers</h2>
<p>As developers we don&#8217;t want to have technical skills nobody needs, and instead we generally must build a large enough portfolio of skills to accommodate the more businesses and projects we can to reduce the risk of being left behind.<br />
So if you are an experienced WPF developer and you have to choose between extending your WPF skills to become an expert or starting to gain new skills for WinRT development then IMHO you should choose the second option.<br />
Of course you&#8217;ll probably be able to do both like me, but WinRT should be somewhere on your TODO list but not your priority either.</p>
<p>Or you could continue in WPF waiting for the market to lack WPF developers, like is the case for older technologies like COBOL and VB6, but I fear you&#8217;ll have to wait a decade before it happens, because, with the important development of IT in businesses, for any technology there is a lot of developers on the market, particularly for mainstream technologies like WPF, so I wouldn&#8217;t count on it.</p>
<p>Don&#8217;t be demoralized or upset by this nth brand new technology, this is the business model of our industry: it needs to create new things all the time (remember SOA that poured a ton of money from businesses to the pockets of IT companies, their employees, their shareholders and contractors) to sell them to customers just as Apple does with its iPhone 1, 2, 3, &#8230; and now 6 and soon 42, this is how it works and fortunately we, as developers, are on the good side of the barrier, we can make a living from this entropy, and objectively all these new technologies enhance the life of businesses and individuals.</p>
<h1>Conclusion</h1>
<p>I think that the sum of all these facts is pretty clear: <strong>WPF is past and present</strong>, in the near future it will be in direct competition with WinRT, but later if WinRT gets some traction and enough market shares then <strong>WPF may become kind of deprecated like VB6 or WinForms</strong>.</p>
<p>Above all don&#8217;t be in denial, and have a clear picture of what happens, do not eliminate the pessimistic facts from your mind.<br />
Do not expect a revival of WPF, there is no such thing in IT (well OK COM is kind of back in WinRT ;)), WPF is objectively not tailored for the new trends, the brand new stuff is.</p>
<p>Of course the picture is not all black: <strong>WPF is not dead and obsolete nor dying and obsolescent</strong>, it has just reached its peak and might slowly fade as the businesses migrate their infrastructure to Windows 8+ allowing them to choose WinRT for their future developments.</p>
<p><strong>Be pragmatic and transparent</strong>: use WPF while it brings value to your clients and warn them about these facts, and help them prepare for the future.<br />
I&#8217;ve myself updated my training material by interleaving WinRT chunks in my WPF training, and adding a slide with a summary of these facts, highlighting them depending on their significance.</p>
<p><strong>But IMHO you should not invest too much in WinRT either.</strong><br />
Why? Because the more I play with WinRT and think about it the more I see it less and less useful:</p>
<ul>
<li>if you develop a LOB application, your only target is probably Windows PC, and you need to be compatible with pre Windows 8 systems, at least Windows 7, so WinRT is clearly not an option, and you must use WPF,</li>
<li>if you want to target tablets and phones you can&#8217;t forget about 90% of the market, iOS and Android, so WinRT is not an option, and you must use either the web stack (JavaScript/HTML/CSS) or native cross-platform frameworks like Xamarin (C#) or QT (C++).</li>
</ul>
<p>So for most use-cases WinRT is not an option.</p>
<p>Moreover you should note that Microsoft is heavily investing in the later technologies.</p>
<p>It&#8217;s probably too early to ask yourself &#8220;<strong><em>Is WinRT (as a final developer platform) dead ?</em></strong>&#8221; but I would be quite surprised if WinRT manages to get some traction and becomes a major development platform.</p>
<p>IMHO WinRT is only a good platform for the Microsoft teams because it allows them to share code between the different flavors of the Windows OS, mimicking the effort of Apple; but for the final developer the use-cases for WinRT are way too limited: sharing some code between PC, tablets and phones but only for Windows devices.<br />
Probably some businesses may need only that but I doubt there is many because nowadays applications are often accessed from personal employees&#8217; devices (BYOD) which can be anything and probably some iOS or Android.</p>
]]></content:encoded>
							<wfw:commentRss>http://pragmateek.com/is-wpf-dead-the-present-and-future-of-wpf/feed/</wfw:commentRss>
		<slash:comments>117</slash:comments>
							</item>
		<item>
		<title>Book review : &#8220;MCSD Certification Toolkit (Exam 70-483): Programming in C#&#8221;</title>
		<link>http://pragmateek.com/book-review-mcsd-certification-toolkit-exam-70-483-programming-in-c/</link>
				<comments>http://pragmateek.com/book-review-mcsd-certification-toolkit-exam-70-483-programming-in-c/#comments</comments>
				<pubDate>Sun, 07 Sep 2014 15:04:28 +0000</pubDate>
		<dc:creator><![CDATA[pragmateek]]></dc:creator>
				<category><![CDATA[.Net Development]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[CodeProject]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[WinRT]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[70-483]]></category>
		<category><![CDATA[API]]></category>
		<category><![CDATA[book]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[certification]]></category>
		<category><![CDATA[debug]]></category>
		<category><![CDATA[LINQ]]></category>
		<category><![CDATA[multi-threading]]></category>
		<category><![CDATA[pattern]]></category>
		<category><![CDATA[review]]></category>
		<category><![CDATA[security]]></category>
		<category><![CDATA[Visual Studio]]></category>

		<guid isPermaLink="false">http://pragmateek.com/?p=3218</guid>
				<description><![CDATA[Introduction I&#8217;ve recently passed the Microsoft 70-483 &#8220;Programming in C#&#8221; certification which is one of the entry point into the .Net and WinRT developers certification cycles. To be well prepared I&#8217;ve read the two books entirely dedicated to this certification &#8230; <a href="http://pragmateek.com/book-review-mcsd-certification-toolkit-exam-70-483-programming-in-c/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
								<content:encoded><![CDATA[<p></p>
<p><a href="http://www.amazon.com/gp/product/1118612094/ref=as_li_tl?ie=UTF8&#038;camp=1789&#038;creative=9325&#038;creativeASIN=1118612094&#038;linkCode=as2&#038;tag=pragmateekcom-20&#038;linkId=2RRWI6ZAGJVB5MSA"><img border="0" src="http://ws-na.amazon-adsystem.com/widgets/q?_encoding=UTF8&#038;ASIN=1118612094&#038;Format=_SL250_&#038;ID=AsinImage&#038;MarketPlace=US&#038;ServiceVersion=20070822&#038;WS=1&#038;tag=pragmateekcom-20" ></a><img src="http://ir-na.amazon-adsystem.com/e/ir?t=pragmateekcom-20&#038;l=as2&#038;o=1&#038;a=1118612094" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /></p>
<h1>Introduction</h1>
<p>I&#8217;ve recently passed the <strong>Microsoft 70-483 &#8220;Programming in C#&#8221; certification</strong> which is one of the entry point into the <strong>.Net</strong> and <strong>WinRT</strong> developers certification cycles.<br />
To be well prepared I&#8217;ve read the two books entirely dedicated to this certification : <a href="http://www.amazon.com/gp/product/1118612094/ref=as_li_tl?ie=UTF8&#038;camp=1789&#038;creative=9325&#038;creativeASIN=1118612094&#038;linkCode=as2&#038;tag=pragmateekcom-20&#038;linkId=EEH7AAW2IMI5B4HQ">MCSD Certification Toolkit (Exam 70-483): Programming in C#</a><img src="http://ir-na.amazon-adsystem.com/e/ir?t=pragmateekcom-20&#038;l=as2&#038;o=1&#038;a=1118612094" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /> and <a href="http://www.amazon.com/gp/product/0735676828/ref=as_li_tl?ie=UTF8&#038;camp=1789&#038;creative=9325&#038;creativeASIN=0735676828&#038;linkCode=as2&#038;tag=pragmateekcom-20&#038;linkId=DRULA5VEVCK6LDQS">Exam Ref 70-483: Programming in C#</a><img src="http://ir-na.amazon-adsystem.com/e/ir?t=pragmateekcom-20&#038;l=as2&#038;o=1&#038;a=0735676828" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" />.<br />
I strongly recommend you read both of them if you intend to pass the certification.<br />
Indeed both have been my main material to prepare for the certification and they have perfectly done the job.</p>
<p>This article is a complete review of <a href="http://www.amazon.com/gp/product/1118612094/ref=as_li_tl?ie=UTF8&#038;camp=1789&#038;creative=9325&#038;creativeASIN=1118612094&#038;linkCode=as2&#038;tag=pragmateekcom-20&#038;linkId=EEH7AAW2IMI5B4HQ">MCSD Certification Toolkit (Exam 70-483): Programming in C#</a><img src="http://ir-na.amazon-adsystem.com/e/ir?t=pragmateekcom-20&#038;l=as2&#038;o=1&#038;a=1118612094" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" />.<br />
This is the first book you should read because I think this is the one that will best prepare you to get the certification, but paradoxically the worst from a technical point of view, and you will quickly understand why.</p>
<p><span id="more-3218"></span></p>
<p>It&#8217;s unfortunately the biggest flaw of this book: it contains a lot of technical errors, ranging from the basic <strong>misuse of words</strong> that only experts will spot and innocuous for neophyte, to <strong>bad practices</strong>, including wrong affirmations, and this is more annoying. And sometimes inside a section you have both some really good content along with really bad content.</p>
<p>This article is not a complete errata, because I&#8217;ve not taken note of every single error, but I&#8217;ll try to illustrate the main issues in order to establish a typology without being exhaustive.</p>
<p>I&#8217;ve chosen to present the worst content first, the <strong>bad practices</strong>, to go to the best, the <strong>good practices</strong>, because this book is equally full of really good technical content that is perfect for the certification and in your daily job as a developer.</p>
<h1>The bad parts</h1>
<h2>Some bad practices</h2>
<p>Teaching <strong>bad practices</strong>, especially when a big part of your audience is made of non experienced developers, is probably the worst thing a technical book can do.</p>
<p>However, let&#8217;s be honest, fortunately there is few bad practices in this book and as it does not pretend to be a technical reference this is not unacceptable.</p>
<p>As an example <strong>naming conventions</strong> are often not respected, so we have methods named <code>displayName</code>, <code>concatenateName</code> or <code>square</code>, which would imply that the author of this code is a recent Java defector. I won&#8217;t judge it as I&#8217;ve myself followed the same path and it took me some time before I completely accept and apply these conventions.</p>
<p>Less innocuous is the modification of the state of a <strong>value type instance</strong> which demonstrates an unfamiliarity with the subtleties of this category of types. But in the author(s) defense a minority of C#/.Net/WinRT developers are aware of this &#8220;issue&#8221;.</p>
<p>Still concerning value types the book states it&#8217;s better to use arrays of references than arrays of values because values would be copied. It&#8217;s completely wrong because arrays are themselves reference types so are manipulated through references, hence in both cases there is no copy involved. Then this is not a good reason to use the &#8220;by reference&#8221; semantics, though by default this is the one we should choose.</p>
<p>As for the design of classes the book mixes business data with purely technical treatments, like accessing a database, instead of decoupling them.<br />
Decoupling is yet the ABC, and would has cost nothing there, so there is no reason not to demonstrate it to beginners.<br />
But in the book&#8217;s defense the certification&#8217;s questions are far from being exemplary in this regard.</p>
<p>Finally when demonstrating <strong>ADO.Net</strong> most of the examples don&#8217;t leverage the <code><strong>using</strong></code> block to control the range of the <strong>connections</strong> and <strong>commands</strong> objects, though this best practice is discussed later in a dedicated sidebar.</p>
<h2>Some errors</h2>
<p>A little less serious are <strong>purely technical errors</strong> like the affirmation that the current element in a <code><strong>foreach</strong></code> loop must have the correct type, which is wrong, and it&#8217;s kind of &#8220;dangerous&#8221; and the source of a lot of bugs: <code><strong>foreach</strong></code> implicitly converts the value if the type is not correct: e.g. <code><strong>double</strong></code> to <code><strong>int</strong></code>.</p>
<p>Some illustrations are wrong: e.g. for <strong>extension methods</strong> the book speaks of extending the <code><strong>Math</strong></code> class which is useless because it can&#8217;t be instantiated because it is a <code><strong>static class</strong></code>, and it&#8217;s really no luck for the authors because this class is more an exception than the rule, so a really bad draw.</p>
<p>&#8220;<code><strong>partial</strong></code>&#8221; classes are described as generating many files inside the same <strong>assembly</strong> whereas they are all aggregated by the <strong>C# compiler</strong> in a single class whose byte-code is integrated as a whole to the <strong>assembly</strong>.</p>
<p>We also &#8220;learn&#8221; that we can set an instance of a <strong>value type</strong> to <code><strong>null</strong></code> which is completely wrong: <code><strong>null</strong></code> makes sense only for a <strong>reference</strong> to an instance of a <strong>reference type</strong> (and <strong>nullable types</strong>).</p>
<p>The book states that instances of value types are always stored on the <strong>stack</strong>: wrong, they can be <strong>inlined</strong> inside instances of reference types in the <strong>heap</strong>, but this is a popular belief in the community so we can&#8217;t blame the authors.</p>
<p>More anecdotal we are taught that the <code><strong>int</strong></code> type can store values up to 4 294 967 286 whereas the limit is half of that.</p>
<p>More annoying, but again a popular belief, the book states there is 2 ways to <strong>pass parameters</strong>: by copy for value types and by reference for reference types, sounds good but wrong, all is done by copy, including copy of reference for reference types, and if you want to pass by reference you must use dedicated <strong>ref</strong> and <strong>out</strong> markers.</p>
<p>But more original is the fact that &#8220;<strong>abstract</strong>&#8221; <strong>methods</strong> would be referred to with the synonym &#8220;<strong>virtual</strong>&#8221; <strong>methods</strong> whereas they are two concepts related but distinct: an abstract method can be considered as virtual, but not in the other direction. So maybe an issue with the understanding of fundamental concepts of <strong>object oriented programming</strong> concepts which would confirm my hypothesis of a strong Java bias: Java developers are those who use the more virtual methods but also those who less understand what they are and how they differ from abstract methods (relatively to <strong>C++</strong> and <strong>C#</strong> developers). Paradoxal? No when we know that by default all the instance methods are virtual in Java so a Java developer will never have to write the word &#8220;<code><strong>virtual</strong></code>&#8221; whereas C++ and C# developers must be explicit.</p>
<h2>Some approximations</h2>
<p>While I agree that some simplifications are harmless for the novice and can avoid throwing too many information at once or making them doubt, I consider that ideally one should not prepare a certification only for the sticker but above all to confirm a real expertise, and to learn new things, and this requires some technical accuracy.</p>
<p>Here is an example of this kind of harmless error that demonstrates a lack of full understanding of the language: the last part of the <code><strong>for</strong></code> loop is described as carrying on an instruction expressing counting (<code><strong>++</strong></code>, <code><strong>*=</strong></code>, <code><strong>-=</strong></code>&#8230;) which is wrong, it can even be missing.<br />
Of course a lot of talented developers can have a brilliant professional career by believing that without any consequence on the quality of their work and their productivity.</p>
<p>Another example of the same type is the description of the <code><strong>while</strong></code> and <code><strong>do-while</strong></code> loops as two completely distinct entities whereas they are the two faces of the same coin.</p>
<p>Similarly when presenting for the first time the <strong>extension methods</strong> it is said that their purpose is to extend classes without recompiling them, which is only a relatively anecdotal point.<br />
Fortunately in this case the correct definition is given in another section, hence the importance of reading the book entirely.</p>
<p>Comparing the <code><strong>for</strong></code> <strong>loop</strong> and the <code><strong>foreach</strong></code> <strong>loop</strong> the book states the latter is there when we don&#8217;t know the number of elements whereas this is more the lack of an <strong>indexer</strong> that will decide of the use of <code><strong>foreach</strong></code>, and indeed some collections expose their length but don&#8217;t provide an indexer so are best iterated with <code><strong>foreach</strong></code>.</p>
<p>It&#8217;s a pity that developers with this amount of experience uses such approximations as confusing the IDE and the platform: it is said that <strong>Visual Studio</strong> calls the constructors whereas of course this is the role of the <string>CLR</string>, <strong>Visual Studio</strong> does not even compile the code.</p>
<p>Unfortunately developers who are not curious and have never developed outside Visual Studio don&#8217;t understand that when we develop this kind of applications we have 3 actors:<br />
&#8211; <strong>.Net</strong> or <strong>WinRT</strong> which is the underlying platform that provides the types library and the runtime environment (for .Net)<br />
&#8211; <strong>C#</strong> that is the programming language using a compiler that generates some binary code, like byte-code running on the .Net platform<br />
&#8211; <strong>Visual Studio</strong> which is a productivity tool (IMHO the best) which interfaces with C# and .Net/WinRT using tools like <strong>MSBuild</strong>.</p>
<p>According to the book the &#8220;<code><strong>volatile</strong></code>&#8221; marker is there to indicate that the data could be modified by other components that our code, it&#8217;s only partially true, because it shines outside of this context (see another of my articles: <a title="Synchronization, memory visibility and leaky abstractions" href="http://pragmateek.com/synchronization-memory-visibility-and-leaky-abstractions/" target="_blank"><strong>Synchronization, memory visibility and leaky abstractions</strong></a>)<br />
There again the authors are forgiven because it&#8217;s the kind of subtleties you understand by practicing a little <strong>parallel programming</strong> and the majority of .Net and WinRT developers can develop completely ignoring it, and that&#8217;s a good thing.</p>
<p>Similarly seems like the authors are not aware that <code><strong>&amp;</strong></code> is also a valid boolean operator, the difference with <code><strong>&amp;&amp;</strong></code> being that it does not bypass. Unfortunately one of the test question is dedicated to this issue so the test is wrong, which is ironic because at the start of the book there is a long introduction to how tests are designed for the certifications, and one of the prerequisites is they must be non ambiguous.</p>
<p>Some topics seems not well understood like <strong>ORMs</strong> which are described as graphical tools whereas this is not at all their primary use case, as is demonstrated by <strong>Entity Framework</strong> which took a U-turn with the &#8220;<strong>Code First</strong>&#8221; workflow.<br />
As for NHibernate it is said to be an ORM dedicated to other databases and languages whereas its first use-case is the interaction with <strong>SQL Server</strong> from <strong>C#</strong></p>
<h2>Some word misuses</h2>
<p>Usually words <strong>misuses</strong> are not serious, except once again for novices who need to remember rigorous definitions, in order to have points of reference helping them in their learning and the consolidation of their knowledge.</p>
<p>As an example <code><strong>System.Int32</strong></code> (alias <code><strong>int</strong></code> in C#) is referred to as a class instead of simply a type (to avoid speaking about value types), probably a reminiscence of <strong>Java</strong> and its <strong>Integer</strong> type which indeed is a <strong>reference type</strong>.</p>
<p>Concerning <strong>C# structs</strong> some <strong>fields</strong> are defined but are referred to as &#8220;properties&#8221; which will confuse beginners because later in the book the <strong>properties</strong> themselves are of course referred to with this same term.</p>
<p>Often the book uses the term &#8220;class file&#8221; instead of just &#8220;class&#8221;, probably another reminiscence of <strong>Java</strong> which indeed only allows a single public class per source file, but even in Java this is not an accurate term.</p>
<p>Similarly the book speaks of <strong>interface</strong> instances instead of <strong>interface references</strong>, but an interface cannot be instantiated, so again confusing for beginners.</p>
<p>Another not completely mastered topics is the <code><strong>BackgroundWorker</strong></code>: the <code><strong>Invoke</strong></code> method is used in the events handlers <code><strong>ProgressChanged</strong></code> and <code><strong>WorkerCompleted</strong></code> whereas the purpose of the <code><strong>BackgroundWorker</strong></code> is precisely to avoid that by automatically capturing the context, and invoking the handlers on the <strong>UI thread</strong> itself.</p>
<h2>Some minor issues</h2>
<p>As you would expect the book suffers from a blatant lack of proofreading: there is a lot of typos and grammatical errors, but fortunately they never affect the understanding, the context always helping to grasp the content.</p>
<p>Towards the end of the book there is a big bunch of code to demonstrate <strong>validation</strong> and <strong>Windows Forms</strong>.<br />
First I don&#8217;t understand the purpose of dumping such a quantity of code, secondly it concentrates a lot of bad practices: playing with flying values instead of consolidating them in dedicated types, business code directly in the UI event handlers instead of being isolated in dedicated components, background color of controls used to store business data, the validation state of the form, which is a strange practice.</p>
<p>There again the danger is for novices that might learn a lot of bad practices and apply them in their professional context and even teach them to their colleagues.</p>
<p>Some technical terms are defined in the glossaries of some chapters but are never addressed which may mean that some sections have been simply &#8220;forgotten&#8221;.</p>
<p>Some topics are repeated: the section on <strong>delegates</strong>, <strong>anonymous functions</strong> and <strong>lambdas</strong> appears 2 times, with two different texts, so probably 2 authors have worked on it without coordination.</p>
<p>Too much time is dedicated to obsolete components like <code><strong>ArrayList</strong></code> now replaced by their equivalent <strong>generics classes</strong>.</p>
<h1>The good parts</h1>
<p>Listing only errors would be really unfair because this book is full of very good content, some sections are of high quality, worthy of the best technical reference books.</p>
<h2>Some good introductions</h2>
<p>First off the book offers a panorama of the tools used for developing with <strong>C#</strong> in <strong>.Net</strong> or <strong>WinRT</strong>, and many sections are small introductions that allows the reader to quickly understand the ins and outs of a given tool.</p>
<p>The introduction to <strong>parallel programming</strong> is really correct, including a small rundown on the <strong>thread-pool</strong> and its limitations like the inability to make a <strong>join</strong>, and another on the <strong>asynchronous methods</strong> in <strong>C# 5.0</strong>.</p>
<p>The part on <strong>monitors</strong> is perfect to revise but a little too short for a beginner discovering the topics who will probably not understand some concepts like the &#8220;<strong>ready-queue</strong>&#8220;.</p>
<p>The book also has a good introduction to <strong>Entity Framework</strong> and illustrates its use with the &#8220;<strong>Database First</strong>&#8221; <strong>workflow</strong> which is one of the 3 workflows supported by EF.</p>
<p><strong>LINQ</strong> is also well covered and the two syntaxes for building queries are presented: via the mini-language integrated to C# or directly via chaining of methods provided by the <code><strong>Enumerable</strong></code> static class.</p>
<p>The introduction to <strong>security</strong> is really broad while being quite compact and addresses various topics like <strong>hashing</strong>, <strong>symmetric</strong> and <strong>asymmetric cryptography</strong>, and, amongst other topics, <strong>certificates</strong>.<br />
It&#8217;s perfect for developers who like me &#8220;know&#8221; these topics but are not completely aware of how to implement them using <strong>.Net/WinRT</strong>.<br />
And by the way I had one question on this section during the certification exam.</p>
<h2>Some good illustrations</h2>
<p>As an example the use of the <code><strong>do-while</strong></code> <strong>loop</strong> is illustrated with a relevant and recurrent use-case: the reading of input from the console.</p>
<p>Similarly the book provides a non-trivial example for the use of an <strong>enumerator</strong> which helps the reader to understand how the <strong><code>foreach</code> loop</strong> works under the hood.</p>
<p>There is also good examples on <strong>object oriented programming</strong>, particularly on the use of <strong>abstract classes</strong> and <strong>virtual methods</strong>, as well as the notions of <strong>contract</strong> and <strong>interface</strong> (e.g. with <strong>explicit implementations</strong>).</p>
<p>To illustrate the importance of <strong>reflection</strong> the book uses the context of <strong>object relational mapping</strong> which, besides being a relevant use-case, is a great technical demonstration for novices because in 20 lines of code we have a mini <string>ORM</strong>, whereas at first sight we would expect a far heavier implementation.</p>
<h2>Some topics really well covered</h2>
<p>Some topics benefit from a better attention with some really comprehensive technical elements.</p>
<p>This is the case for strings, their immutability and storage management by the <strong>CLR</strong> ((<strong>interning</strong>) being well addressed.</p>
<p>The introduction to the inner workings of <strong>garbage-collection</strong> is short and of high quality, and especially insists on the <strong>non-determinism</strong>, illustrating it with the use of files.<br />
This example helps the reader to get a natural understanding of the goal of <strong>finalizers</strong>/<strong>destructors</strong> and the <strong>disposable pattern</strong>.<br />
The explanations are balanced: enough technical depth to correctly understand the inner workings and acquire some knowledge going beyond the certification, without bogging down the novice with too many subtleties, while exposing the rationales and use-cases.<br />
It&#8217;s one of the best description of this topic I&#8217;ve ever read.</p>
<p>Another example where the content is better and richer than expected for the certification is <strong>CodeDOM</strong> which benefits from a complete and rich demonstration using <strong>C#</strong> and <strong>VB.Net</strong> that goes beyond the canonical example, copy pasted everywhere on the web and books, consisting in compiling an &#8220;Hello world&#8221; program in C#.</p>
<h2>Some contextualization and good practices</h2>
<p>To finish you have to know that the book gives a lot of information that help the reader putting things in perspective, along with some good practices<br />
Even if this is not really useful for the certification which primarily evaluates your capacity to use the tools, not to talk about them, this will help every developer to better understand some tools he uses without a real understanding of them.</p>
<p>For example the rationales of <strong>enumerated types</strong> are really well explained, insisting on the enhancement of <strong>readability</strong> hence <strong>maintainability</strong> of code.</p>
<p>Similarly for <strong>generic types and methods</strong> the book insists on all their benefits like code <strong>reusability</strong>, <strong>type safety</strong> and <strong>performances</strong>.</p>
<p>The introduction of the <strong>encapsulation</strong> concept is really good, invoking <strong>validation</strong> and the use of transformations to avoid SQL injections as relevant use-cases, the latter being less realistic but interesting.</p>
<p>The book puts emphasis on <strong>good practices</strong> like the systematic use of curly braces even when there is only one instruction, typically for the <code><strong>if</strong></code> block.</p>
<p>Often there is good advices like the importance of not exposing sensitive information through <strong>exceptions</strong>, and making them <strong>serializable</strong> if they must cross the boundaries of an <strong>app-domain</strong></p>
<p>Finally the book refers to good additional resources like <a href="http://pinvoke.net" title="pinvoke.net" target="_blank">pinvoke.net</a> which is almost essential when working with <strong>native interop</strong> via <strong>P/Invoke</strong> (<code><strong>DllImport</strong></code>).</p>
<h1>Global assessment</h1>
<p>The principal interest of this book is that it presents a large spectrum of topics, and IMHO it is complete with regards to the certification official program.<br />
During the certification I&#8217;ve not encountered a question whose topic was not discussed in this book.</p>
<p>Depending on the reader current skills in C#/.Net/WinRT this book will profit him more or less:<br />
&#8211; if you are really strong, <strong>senior</strong> with at least 5 years of experience, then you&#8217;ll be able to sort the wheat from the chaff (the nugget from the errors), and this book will be one of your best ally to pass the certification<br />
&#8211; if you have an <strong>intermediate level</strong>, with strong basis this book may help you to reach the next level, because it lists the important technical topics you have to work on,<br />
&#8211; but if you are a <strong>beginner</strong>, ignoring the fact it may be too soon to pass the certification, this book might be dangerous if you naively learn some errors and bad practices, so you must double your vigilance and in case of doubt do not hesitate to ask to experimented developers.</p>
<p>As for me I could divide the content of this book as follow:</p>
<ul>
<li>75% was made of stuff I knew the book helped me to revise,</li>
<li>15% was about topics I had forgotten and I was happy to have taken the time to read this book entirely because missing 15% of the program is a lot, it represents half the error margin you have for this exam (you must have at least 700/1000),</li>
<li>10% were topic I didn&#8217;t know, I may have heard of, but that I had never used like <strong>WCF Data Service</strong> or the possibility to inline options inside <strong>regular expressions</strong>, or some best practices I had missed like using labels with <code><strong>#endregion</strong></code> directives</li>
</ul>
<p>So I&#8217;ve really learnt a lot by reading this book, some things less important than others, but every piece of knowledge is good to take when you aim at expertise.</p>
<h1>Conclusion</h1>
<p>As you&#8217;ve seen the content of &#8220;<strong>MCSD Certification Toolkit (Exam 70-483): Programming in C#</strong>&#8221; is very uneven.<br />
What I don&#8217;t understand is why the ebook version has still so much errors despite the many strong reactions, IMHO often a little disproportioned, of offended and disappointed readers.</p>
<p><strong>So should you read this book?</strong><br />
If you are willing to pass the <strong>70-483 certification</strong> the answer is a strong &#8220;yes&#8221; because this book correctly summarizes all the technical points you&#8217;ll need to know to success, and it will help you find where you have some weaknesses you should work on.<br />
This is also a choice by default because there is not really any alternative.</p>
<p>However if you need a technical book to develop you current skills and gain new ones then I don&#8217;t recommend this book as you might learn some bad practices, and reading a book being suspicious is really not good for memorization because we tend to not believe anything.</p>
<p>Above all don&#8217;t do as other readers who have stopped to read it after a few pages or chapters upset by the accumulation of errors, and for two reasons:<br />
&#8211; the quality of this book really enhances chapter after chapter, and while I&#8217;ve found a bunch of errors in the first part, I&#8217;ve found almost nothing towards the end, as if the first part was written by a novice developer, the middle by a more experimented one, and the final part by an expert.<br />
&#8211; even in the parts full of errors there are some important informations and even some nuggets.<br />
So even if you are considered an expert this book will learn you something and it would be a pity to not read it to pass the certification.</p>
<p>What is sure is that this book is the result of a huge work that deserves a lot of respect, and better to have imperfect resources than no resource at all.</p>
<p><strong>My final rating</strong><br />
Rating this book is quite difficult because on one side I consider the accumulation of technical errors and approximations really harmful for the novice readers who probably represent an important part of this book&#8217;s audience, but on the other side this book perfectly does the job of preparing the reader for the certification.</p>
<p>If it was a book with the pretention of being a technical reference I would note it quite severely: 5/10.<br />
But for a reader only willing to obtain the certification it is well worth 9/10.<br />
So I&#8217;ve finally rated it 8/10, 4 out of 5 stars on Amazon, because I&#8217;ve considered that passing the certification is really the point of this book which is not a technical reference, and so I&#8217;ve overweighted this aspect.</p>
]]></content:encoded>
							<wfw:commentRss>http://pragmateek.com/book-review-mcsd-certification-toolkit-exam-70-483-programming-in-c/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
							</item>
		<item>
		<title>[FRENCH] Revue du livre &#8220;MCSD Certification Toolkit (Exam 70-483): Programming in C#&#8221;</title>
		<link>http://pragmateek.com/french-revue-du-livre-mcsd-certification-toolkit-exam-70-483-programming-in-c/</link>
				<comments>http://pragmateek.com/french-revue-du-livre-mcsd-certification-toolkit-exam-70-483-programming-in-c/#comments</comments>
				<pubDate>Sat, 02 Aug 2014 21:27:08 +0000</pubDate>
		<dc:creator><![CDATA[pragmateek]]></dc:creator>
				<category><![CDATA[.Net Development]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[WinRT]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[book]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[certification]]></category>
		<category><![CDATA[french]]></category>
		<category><![CDATA[review]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[winrt]]></category>

		<guid isPermaLink="false">http://pragmateek.com/?p=3129</guid>
				<description><![CDATA[Introduction J’ai tout récemment passé et obtenu la certification Microsoft 70-483 &#8220;Programming in C#&#8221; qui est l&#8217;un des points d’entrée des cycles de certification développeur .Net et WinRT. Pour m&#8217;y préparer j&#8217;ai notamment lu les 2 livres qui y sont &#8230; <a href="http://pragmateek.com/french-revue-du-livre-mcsd-certification-toolkit-exam-70-483-programming-in-c/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
								<content:encoded><![CDATA[<p></p>
<p><a title="MCSD Certification Toolkit (Exam 70-483): Programming in C#" href="http://www.amazon.fr/gp/product/B00CP2PZB0/ref=as_li_qf_sp_asin_il_tl?ie=UTF8&amp;camp=1642&amp;creative=6746&amp;creativeASIN=B00CP2PZB0&amp;linkCode=as2&amp;tag=pragmateekcom-21&amp;linkId=34OXSYNQZ3WEKRCW" target="_blank"><img alt="Book cover" src="http://ecx.images-amazon.com/images/I/51287R7FLPL._SS500_.jpg" /></a></p>
<h1>Introduction</h1>
<p>J’ai tout récemment passé et obtenu la <strong>certification Microsoft 70-483 &#8220;Programming in C#&#8221;</strong> qui est l&#8217;un des points d’entrée des cycles de certification développeur <strong>.Net</strong> et <strong>WinRT</strong>.<br />
Pour m&#8217;y préparer j&#8217;ai notamment lu les 2 livres qui y sont dédiés (en anglais) : <a title="MCSD Certification Toolkit (Exam 70-483): Programming in C#" href="http://www.amazon.fr/gp/product/B00CP2PZB0/ref=as_li_qf_sp_asin_il_tl?ie=UTF8&amp;camp=1642&amp;creative=6746&amp;creativeASIN=B00CP2PZB0&amp;linkCode=as2&amp;tag=pragmateekcom-21&amp;linkId=34OXSYNQZ3WEKRCW" target="_blank"><strong>MCSD Certification Toolkit (Exam 70-483): Programming in C#</strong></a> et <a href="http://www.amazon.fr/gp/product/0735676828/ref=as_li_qf_sp_asin_tl?ie=UTF8&amp;camp=1642&amp;creative=6746&amp;creativeASIN=0735676828&amp;linkCode=as2&amp;tag=pragmateekcom-21" target="_blank"><strong>Programming in C#: Exam Ref 70-483</strong></a> dont je vous conseille vivement la lecture.<br />
Ils ont en effet constitué mon support principal pour la préparation de la certification et ont bien remplis leur office.</p>
<p>Cet article est une revue complète de <a title="MCSD Certification Toolkit (Exam 70-483): Programming in C#" href="http://www.amazon.fr/gp/product/B00CP2PZB0/ref=as_li_qf_sp_asin_il_tl?ie=UTF8&amp;camp=1642&amp;creative=6746&amp;creativeASIN=B00CP2PZB0&amp;linkCode=as2&amp;tag=pragmateekcom-21&amp;linkId=34OXSYNQZ3WEKRCW" target="_blank"><strong>MCSD Certification Toolkit (Exam 70-483): Programming in C#</strong></a>.<br />
C&#8217;est le 1er livre que vous devriez lire, je pense celui qui prépare le mieux à la certification, mais paradoxalement le moins bon techniquement, et vous allez vite comprendre pourquoi.</p>
<p><span id="more-3129"></span></p>
<p>C&#8217;est malheureusement le gros point noir de ce livre : il est parsemé d&#8217;<strong>erreurs techniques</strong>, allant du simple <strong>abus de langage</strong> que seuls les experts remarqueront et sans conséquence pour les néophytes, aux  <strong>mauvaises pratiques</strong>, en passant par les affirmations contraires à la réalité, et là c&#8217;est plus embêtant. Parfois au sein d&#8217;une même section se côtoient le pire et le meilleur.</p>
<p>Ce post ne se veut pas un errata complet puisque je n&#8217;ai pas pris note de toutes les erreurs mais des principales le but étant surtout d&#8217;en faire la typologie sans être exhaustif.</p>
<p>J&#8217;ai choisi de partir du pire, les <strong>mauvaises pratiques</strong>, pour aller vers le meilleur, les <strong>bonnes pratiques</strong>, car ce livre reste en grande majorité rempli de très bons éléments techniques.</p>
<h1>Des défauts</h1>
<h2>Des mauvaises pratiques</h2>
<p>Dispenser de <strong>mauvaises pratiques</strong>, surtout quand une bonne partie de l&#8217;audience est constituée de développeurs non expérimentés, est sûrement ce qu&#8217;il y a de pire pour un livre technique.</p>
<p>Cependant soyons honnête il y en a heureusement très peu dans ce livre et comme il ne se prétend pas être une référence technique ce n&#8217;est pas du tout rédhibitoire.</p>
<p>Par exemple les <strong>conventions de nommage</strong> sont souvent oubliées ainsi on se retrouve avec des méthodes <code>displayName</code>, <code>concatenateName</code> ou encore <code>square</code>, ce qui semblerait indiquer que l&#8217;auteur ayant écrit ces codes est un récent transfuge de Java vers .Net. Je ne vais pas jeter la pierre ayant moi même suivi ce chemin et ayant eu un petit temps d&#8217;adaptation à ces conventions.</p>
<p>Un peu plus grave est la<strong> modification de l&#8217;état</strong> d&#8217;une instance de <strong>type valeur</strong> ce qui démontre une méconnaissance des subtilités de cette catégorie de type. Mais à la décharge du/des auteurs une minorité de développeurs C#/.Net/WinRT en a conscience.</p>
<p>Toujours à propos des types valeurs il est affirmé qu&#8217;il vaut mieux utiliser des <strong>tableaux de références</strong> plutôt que des <strong>tableaux de valeurs</strong> car les valeurs sont copiées. C&#8217;est tout simplement faux puisque les tableaux eux-mêmes sont manipulés par référence donc dans les deux cas il n&#8217;y a pas de copie. Ce n&#8217;est donc pas une bonne raison d&#8217;utiliser la sémantique de référence pour un type même si par défaut c&#8217;est celle-ci qu&#8217;il faut choisir.</p>
<p>Au niveau de la conception des classes le livre mélange allègrement données métiers et traitements technico-techniques, comme l&#8217;accès à une base de données, au lieu de les découpler.<br />
Le <strong>découplage</strong> est pourtant le b.a.-ba et n&#8217;aurait rien coûté dans ce cas, donc pas de raison de ne pas le démontrer à des débutants.<br />
Mais à la décharge du livre les questions de la certification officielle ne sont pas exemplaires à cet égard.</p>
<p>Enfin lors de la démonstration d&#8217;<strong>ADO.Net</strong> la plupart des exemple n&#8217;explicitent pas la portée des <strong>connexions</strong> et des <strong>commandes</strong> à l&#8217;aide du bloc <code><strong>using</strong></code>, bien que cette bonne pratique soit abordée plus loin dans un encart.</p>
<h2>Des erreurs</h2>
<p>Un peu moins graves sont les <strong>erreurs technico-techniques</strong> comme l&#8217;affirmation que l&#8217;élément courant de la boucle <code><strong>foreach</strong></code> doit avoir le bon type, ce qui est faux, et c&#8217;est d&#8217;ailleurs &#8220;dangereux&#8221; et source de nombreux bugs : <code><strong>foreach</strong></code> convertit implicitement si le type n&#8217;est pas correct : par exemple de <code><strong>double</strong></code> en <code><strong>int</strong></code>.</p>
<p>Certaines illustrations sont fausses : e.g. pour les <strong>méthodes d&#8217;extension</strong> le livre parle d&#8217;étendre la classe <code><strong>Math</strong></code> ce qui est inutile car elle ne peut être instanciée car elle est <code><strong>static</strong></code>, et là c&#8217;est vraiment pas de chance pour les auteurs parce que c&#8217;est une exception plutôt que la règle, mauvaise pioche comme on dit.</p>
<p>Une classe &#8220;<code><strong>partial</strong></code>&#8221; est décrite comme générant plusieurs fichiers au sein du même <strong>assembly</strong> alors qu&#8217;ils sont tous agrégés par le <strong>compilateur C#</strong> en une classe unique intégrée à l&#8217;<strong>assembly</strong>.</p>
<p>On nous apprend également que l&#8217;on peut setter une instance de <strong>type valeur</strong> à <code><strong>null</strong></code> ce qui est complètement faux : <code><strong>null</strong></code> n&#8217;a de sens que pour une référence vers une instance de <strong>type référence</strong>.</p>
<p>Le livre affirme que les instances de type valeur sont systématiquement stockées sur la <strong>pile</strong> : c&#8217;est faux, elles peuvent aussi être <strong>inlinées</strong> au sein d&#8217;instances de type référence sur le <strong>tas</strong>, mais c&#8217;est une croyance malheureusement très répandue dans la communauté donc difficile de les blâmer.</p>
<p>Plus anecdotique on nous dit que le type <code><strong>int</strong></code> peut stocker des valeurs allant jusqu&#8217;à 4 294 967 286 alors que ce n&#8217;est que la moitié.</p>
<p>Plus embêtant mais très répandu on apprend qu&#8217;il y a 2 types de <strong>passage de paramètre</strong> : par copie pour les types valeur et par référence pour les types référence, ça sonne bien mais c&#8217;est faux, tout se fait par copie, y compris donc copie de référence pour les types référence.</p>
<p>Complètement original par contre est le fait que les <strong>méthodes</strong> &#8220;<strong>abstraites</strong>&#8221; seraient également désignées sous le terme synonyme de <strong>méthodes</strong> &#8220;<strong>virtuelles</strong>&#8221; alors que ce sont 2 concepts liés mais distincts : une méthode abstraite peut être considérée comme virtuelle, mais pas l&#8217;inverse. Donc là un souci de compréhension des concepts de <strong>programmation orientée objet</strong> ce qui semble aussi confirmer mon hypothèse quant à un fort biais Java : les développeurs Java sont ceux qui écrivent le plus de méthodes virtuelles mais sont ceux qui savent le moins ce qu&#8217;elles sont (par rapport aux développeurs <strong>C++</strong> et <strong>C#</strong>). Paradoxal ? Non quand on sait que par défaut toutes les méthodes d&#8217;instance en Java sont virtuelles donc jamais un développeur Java n&#8217;aura a écrire &#8220;<code><strong>virtual</strong></code>&#8220;.</p>
<h2>Des approximations</h2>
<p>Certaines simplifications sont sans dangers pour les débutants car cela peut éviter de leur donner trop d&#8217;informations d&#8217;un coup ou les faire douter mais idéalement on ne prépare pas une certification seulement pour le macaron mais avant tout pour asseoir une véritable expertise et également apprendre de nouvelles choses, ce qui nécessite un peu de précision.</p>
<p>Voici un exemple d&#8217;erreur qui est sans gravité mais démontre une méconnaissance du langage : la dernière partie de la boucle <code><strong>for</strong></code> est décrite comme ne pouvant servir qu&#8217;à l&#8217;expression d&#8217;instruction de comptage (<code><strong>++</strong></code>, <code><strong>*=</strong></code>, <code><strong>-=</strong></code>&#8230;) ce qui est faux, elle peut même être absente.<br />
Je vous rassure de nombreux développeurs talentueux peuvent passer toute leur carrière en le croyant sans incidence sur la qualité de leur travail et leur productivité.</p>
<p>Un autre exemple de ce type est la description des boucles <code><strong>while</strong></code> et <code><strong>do-while</strong></code> comme deux entités bien distinctes alors qu&#8217;elles ne sont que les deux faces d&#8217;une même médaille.</p>
<p>De même en présentant la 1ère fois les <strong>méthodes d&#8217;extension</strong> il est dit que leur objet est l&#8217;extension d&#8217;une classe sans la recompiler, ce qui n&#8217;est qu&#8217;un aspect plutôt anecdotique.<br />
Heureusement dans ce cas, la bonne définition est donnée dans une autre section, d&#8217;où l&#8217;importance de tout lire.</p>
<p>De même il est avancé que l&#8217;objet de <code><strong>foreach</strong></code> par rapport à la <strong>boucle</strong> <code><strong>for</strong></code> est la possibilité d&#8217;itérer quand on ne connait pas le nombre d&#8217;éléments de la collection, alors que c&#8217;est surtout l&#8217;absence d&#8217;un <strong>indexeur</strong> qui conditionne son utilisation, et en effet d&#8217;autres collections nous indiquent bien leur longueur mais ne fournissent pas d&#8217;indexeur donc sont mieux exploitées par un <code><strong>foreach</strong></code>.</p>
<p>D&#8217;autres approximations sont dommages pour des développeurs ayant une certaine expérience comme affirmer que c&#8217;est <strong>Visual Studio</strong> qui appelle les constructeurs alors que c&#8217;est bien sûr le <strong>CLR</strong>.<br />
Malheureusement les développeurs non curieux qui n&#8217;ont jamais mis le nez hors de Visual Studio ont du mal à comprendre que quand on développe ce type d&#8217;applications on a 3 acteurs :<br />
&#8211; <strong>.Net</strong> ou <strong>WinRT</strong> qui est la plateforme sous-jacente et fournit notamment la bibliothèque de types et l&#8217;environnement d&#8217;exécution<br />
&#8211; <strong>C#</strong> qui est un langage possédant un compilateur capable de générer du code s&#8217;exécutant sur la plateforme .Net<br />
&#8211; <strong>Visual Studio</strong> qui est un outil de productivité (le meilleur à mon avis) qui s&#8217;interface avec C# et .Net/WinRT via <strong>MSBuild</strong> notamment.</p>
<p>Le marqueur &#8220;<code><strong>volatile</strong></code>&#8221; est sensé indiquer que le code peut être modifié par d&#8217;autres composants que notre code, c&#8217;est partiellement vrai, mais il est aussi très utile en dehors de ce contexte (cf un autre de mes articles : <a title="Synchronization, memory visibility and leaky abstractions" href="http://pragmateek.com/synchronization-memory-visibility-and-leaky-abstractions/" target="_blank"><strong>Synchronization, memory visibility and leaky abstractions</strong></a>).<br />
Là encore les auteurs sont pardonnés parce que c&#8217;est une subtilité qu&#8217;on ne voit qu&#8217;en pratiquant un peu la <strong>programmation parallèle</strong> et la majorité des développeurs .Net passe à travers et c&#8217;est très bien comme ça.</p>
<p>De même les auteurs n&#8217;ont pas conscience que <code><strong>&amp;</strong></code> est aussi un opérateur booléen valide mais ne <strong>court-circuitant</strong> pas contrairement à <code><strong>&amp;&amp;</strong></code>. Et malheureusement une des questions d&#8217;un test est consacrée à ce sujet, donc le test est faux, ce qui ironiquement est contraire à la façon dont sont décrits les tests au début du livre comme devant être non ambigus notamment.</p>
<p>Certains sujets semblent non maîtrisés comme les <strong>ORMs</strong> qui sont décrits comme des outils graphiques alors que ce n&#8217;est pas du tout le 1er cas d&#8217;utilisation, comme le démondre le virage &#8220;<strong>Code First</strong>&#8221; d&#8217;<strong>Entity Framework</strong>. <strong>NHibernate</strong> est quant à lui désigné comme faisant partie des ORMs dédiés aux autres bases de données et langages alors que son 1er cas d&#8217;utilisation est l&#8217;interaction avec <strong>SQL Server</strong> depuis <strong>C#</strong>.</p>
<h2>Des abus de langage</h2>
<p>Les <strong>abus de langage</strong> sont généralement peu graves, sauf là encore pour les débutants qui ont besoin de retenir des définitions rigoureuses, afin d&#8217;établir des repères les aidant dans l&#8217;apprentissage et la consolidation des connaissances.</p>
<p>Par exemple <code><strong>System.Int32</strong></code> (alias <code><strong>int</strong></code> en C#) est désigné comme une classe plutôt que simplement un type (pour éviter de parler de type valeur), là encore sûrement une réminiscence de <strong>Java</strong> et son type <code><strong>Integer</strong></code> qui en effet est un <strong>type référence</strong>.</p>
<p>Pour les <strong>structs C#</strong> des <strong>champs</strong> sont définis mais sont désignés par le terme &#8220;propriété&#8221; ce qui sera source de confusion pour un lecteur débutant puisque plus loin dans le livre les <strong>propriétés</strong> sont bien sûr désignées par ce même terme.</p>
<p>Souvent le livre utilise le terme de &#8220;fichier de classe&#8221; au lieu de &#8220;classe&#8221; tout court, sûrement une autre réminiscence de <strong>Java</strong> où en effet un fichier source ne peut contenir qu&#8217;une classe publique mais même là ça serait un abus de langage.</p>
<p>Dans le même genre le livre parle d&#8217;instance d&#8217;<strong>interface</strong> au lieu de <strong>référence</strong> d&#8217;interface, une interface ne pouvant bien sûr pas être instanciée.</p>
<p>Autre sujet mal maîtrisé, le <code><strong>BackgroundWorker</strong></code> : la méthode <code><strong>Invoke</strong></code> est utilisée dans les gestionnaires des évènements <code><strong>ProgressChanged</strong></code> et <code><strong>WorkerCompleted</strong></code> alors que justement l&#8217;objet du <code><strong>BackgroundWorker</strong></code> est de capturer automatiquement le contexte et donc de les invoquer sur le <strong>thread UI</strong> lui-même.</p>
<h2>Des soucis mineurs</h2>
<p>Accessoirement et comme on pouvait s&#8217;y attendre le livre souffre d&#8217;un manque de relecture, il y a en effet beaucoup de fautes d&#8217;orthographe et de grammaire mais cela n&#8217;affecte pas la compréhension, le contexte permettant toujours de comprendre le propos.</p>
<p>Vers la fin du livre il y a un énorme pâté de code pour démontrer la <strong>validation</strong> en <strong>Windows Forms</strong>. D&#8217;une part je ne comprends pas l&#8217;utilité de dumper un volume aussi gros de code, d&#8217;autre part il est un concentré de mauvaise pratiques comme jongler avec des valeurs volantes au lieu de les consolider dans des types dédiés, placer le code de validation au sein même de l&#8217;UI alors qu&#8217;il aurait sa place dans des composants dédiés ou encore utiliser la couleur de fond d&#8217;un contrôle pour vérifier la validité du formulaire, c&#8217;est un mode de communication plutôt &#8230; amateur!</p>
<p>Là encore le danger est pour les débutants qui risquent de faire le plein de mauvaises pratiques et de les appliquer dans leur environnement professionnel voire les transmettre à leurs collègues.</p>
<p>Des termes techniques sont définis dans le lexique de certains chapitres mais jamais abordés ce qui peut laisser penser que certaines sections ont été &#8220;oubliées&#8221;.</p>
<p>Des sujets sont répétés : la section sur les <strong>délégués</strong>, les <strong>méthodes anonymes</strong> et les <strong>lambdas</strong> apparaît 2 fois, avec deux textes différents, donc sans doute que 2 auteurs ont travaillé dessus sans se coordonner.</p>
<p>Trop de temps est consacré à des composants obsolètes comme les <code><strong>ArrayList</strong></code> remplacés depuis par des équivalents <strong>génériques</strong>.</p>
<h1>Des qualités</h1>
<p>Ne lister que les erreurs serait vraiment injuste car ce livre regorge également de très bons éléments, certaines sections d&#8217;une qualité digne des meilleures références techniques.</p>
<h2>De bonnes introductions</h2>
<p>Tout d&#8217;abord le livre offre un panorama des outils utilisés dans le développement avec <strong>C#</strong> sous <strong>.Net</strong> ou <strong>WinRT</strong>, et de nombreuses sections sont des petites introductions qui permettent au lecteur de rapidement comprendre les tenants et aboutissants d&#8217;un outil.</p>
<p>L&#8217;introduction à la <strong>programmation parallèle</strong> est très correcte avec notamment un petit topo sur le <strong>thread-pool</strong> et ses limitations comme l&#8217;impossibilité d&#8217;effectuer un <strong>join</strong>, et sur les <strong>méthodes asynchrones</strong> de <strong>C# 5.0</strong>.</p>
<p>La partie sur les <strong>moniteurs</strong> est très bien pour réviser mais juste un peu courte pour un débutant découvrant le sujet qui ne saisira pas certains concepts comme la “<strong>ready-queue</strong>”.</p>
<p>Le livre possède aussi une bonne introduction à <strong>Entity Framework</strong> et illustre son utilisation avec le <strong>workflow</strong> &#8220;<strong>Database First</strong>&#8220;.</p>
<p><strong>LINQ</strong> est également bien présenté et aborde les deux syntaxes de construction des requêtes : via le mini-langage intégré à C# ou directement via le chaînage des méthodes fournies par <code><strong>Enumerable</strong></code>.</p>
<p>L&#8217;introduction à la <strong>sécurité</strong> est très complète tout en étant très compacte et aborde des sujets aussi variés que le <strong>hachage</strong>, le <strong>chiffrement symétrique</strong> et <strong>asymétrique</strong>, ou encore les <strong>certificats</strong>.<br />
C&#8217;est parfait pour les développeurs qui comme moi connaissent ces sujet mais ne sont pas complètement au fait de leur implémentation concrète au sein de <strong>.Net/WinRT</strong>.<br />
Et j&#8217;ai d&#8217;ailleurs eu une question sur cette section lors du passage de la certification.</p>
<h2>De bonnes illustrations</h2>
<p>Par exemple l&#8217;illustration de l&#8217;usage de la <strong>boucle</strong> <code><strong>do-while</strong></code> avec la lecture d&#8217;entrées utilisateur est très pertinente et est un cas d&#8217;utilisation réel et récurrent.</p>
<p>De même un exemple non trivial d&#8217;utilisation des <strong>énumérateurs</strong> est fourni ce qui permet de bien comprendre comment les choses fonctionnent sous le capot.</p>
<p>Il y a également de bons exemples sur la <strong>programmation orientée objet</strong>, notamment sur l&#8217;utilisation des <strong>classes abstraites</strong> et des <strong>méthodes virtuelles</strong>, ainsi que la notion de <strong>contrat</strong> et d&#8217;<strong>interface</strong>, e.g. avec les <strong>implémentations explicites</strong>.</p>
<p>Pour illustrer l&#8217;importance de la <strong>réflexion</strong> le livre utilise la problématique du <strong>mapping objet-relationnel</strong> ce qui en plus d&#8217;être très pertinent est une bonne démonstration technique pour les débutants puisqu&#8217;en 20 lignes de code on se retrouve avec un mini <strong>ORM</strong>, alors qu&#8217;au 1er abord on pourrait penser à une implémentation bien plus lourde.</p>
<h2>Des sujets bien traités</h2>
<p>Certains sujets bénéficient d&#8217;un traitement plus en profondeur avec des éléments techniques pointus.</p>
<p>C&#8217;est le cas des chaines de caractères, leur immutabilité et la gestion de leur stockage par le CLR (<strong>interning</strong>) étant bien abordés.</p>
<p>L&#8217;introduction au fonctionnement de la <strong>garbage-collection</strong> est concise et de qualité, et insiste notamment sur le <strong>non-déterminisme</strong>, en l&#8217;illustrant avec l&#8217;utilisation de fichiers.<br />
Ce qui amène à la compréhension instinctive de la finalité des <strong>finaliseurs</strong>/<strong>destructeurs</strong> et du <strong>pattern disposable</strong>.<br />
Les explications sont équilibrées : assez de profondeur technique pour bien comprendre le fonctionnement et acquérir des connaissances allant au delà de la certification, sans noyer le débutant sous trop de subtilités, tout en exposant bien les raisons d&#8217;être et les cas d&#8217;utilisation.<br />
C&#8217;est franchement une des meilleures descriptions que j&#8217;ai vu de ce sujet.</p>
<p>Un autre exemple où le contenu est plus fournis que nécessaire pour la certification est <strong>CodeDOM</strong> qui bénéficie d&#8217;une démonstration riche et complète utilisant <strong>C#</strong> et <strong>VB.Net</strong>, qui va au delà de l&#8217;exemple canonique copié et recopié partout consistant en la compilation d&#8217;un &#8220;Hello world&#8221; utilisant C#.</p>
<h2>De la contextualisation et des bonnes pratiques</h2>
<p>Pour finir il faut savoir que le livre distille pas mal d&#8217;informations qui permettent de mettre les concepts en perspectives, ainsi que des bonne pratiques.<br />
Même si ce n&#8217;est pas vraiment utile pour la certification qui évalue avant tout votre capacité à utiliser les outils et pas à en parler, cela permettra à tout développeur de mieux comprendre les outils qu&#8217;il utilise sans s&#8217;être forcément posé trop de questions.</p>
<p>Par exemple la raison d&#8217;être des <strong>types énumérés</strong> est très bien expliquée en insistant sur l&#8217;amélioration de la <strong>lisibilité</strong> et donc de la <strong>maintenabilité</strong> du code.</p>
<p>De même pour les types et méthodes generics où le livre insiste bien sur tous leurs bienfaits comme la <strong>réutilisation</strong> du code, la <strong>sécurité de typage</strong> et les <strong>performances</strong>.</p>
<p>L&#8217;introduction au principe d&#8217;<strong>encapsulation</strong> est très bonne, évoquant notamment la <strong>validation</strong> comme un cas d&#8217;utilisation pertinent et l&#8217;application de transformations pour par exemple éviter les injections SQL, moins réaliste je pense mais intéressant quand même.</p>
<p>L&#8217;accent est souvent mis sur des <strong>bonnes pratiques</strong> comme l&#8217;utilisation systématique d&#8217;accolades même quand il n&#8217;y a qu&#8217;une seule instruction, pour les blocs <code><strong>if</strong></code> notamment.</p>
<p>Il y a souvent des bon conseils comme l&#8217;importance de ne pas véhiculer d&#8217;information sensible via les <strong>exceptions</strong>, et de les rendre <strong>sérialisables</strong> si elles doivent passer les limites d&#8217;un <strong>app-domain</strong>.</p>
<p>Enfin le livre fait référence à de bonnes ressources complémentaires comme <a href="http://pinvoke.net" title="pinvoke.net" target="_blank">pinvoke.net</a> qui est incontournable quand on fait de l&#8217;<strong>interop native</strong> via <strong>P/Invoke</strong> (<code><strong>DllImport</strong></code>).</p>
<h1>Le bilan</h1>
<p>L&#8217;intérêt principal de ce livre est qu&#8217;il présente une large gamme de sujets, et je pense qu&#8217;il est exhaustif par rapport au programme officiel.</p>
<p>Ce livre profitera plus ou moins au lecteur selon son niveau en C#/.Net/WinRT :<br />
&#8211; si vous avez un très bon niveau, <strong>senior</strong> avec 5 ans d&#8217;expérience, alors vous serez capable de faire la part des choses entre les bonnes informations et les erreurs, et ce livre sera un de vos meilleurs alliés pour passer la certification,<br />
&#8211; si vous avez un niveau <strong>junior confirmé</strong> avec des bases solides ce livre pourra vous aider à passer au niveau intermédiaire ne serait-ce que par l&#8217;énumération de sujets importants et de bons points techniques à travailler,<br />
&#8211; par contre si vous êtes <strong>débutant</strong>, outre le fait qu&#8217;il est sans doute un peu tôt pour passer la certification, ce livre est dangereux si vous assimilez les erreurs et mauvaises pratiques naïvement, donc il faut redoubler de prudence et ne pas hésiter à demander à des développeurs expérimentés en cas de doute.</p>
<p>Me concernant, je pourrais diviser à la louche le contenu comme suit :</p>
<ul>
<li>75% était constitué d&#8217;acquis que le livre m&#8217;a permis de réviser,</li>
<li>15% concernait des sujets que j&#8217;avais oubliés et donc j&#8217;étais bien content d&#8217;avoir pris le temps de lire le livre en entier parce que &#8220;faire l&#8217;impasse&#8221; sur 15% du programme ça fait beaucoup, ça représente en effet la moitié de la marge de manœuvre accordée pour cet examen (il faut avoir 700/1000),</li>
<li>10% concernait des sujets que je ne connaissais pas, dont j&#8217;avais pu entendre parler mais que je n&#8217;avais jamais utilisés comme <strong>WCF Data Service</strong> ou bien la possibilité d&#8217;utiliser des options inlinées dans les <strong>expressions rationnelles</strong>, ou encore des bonnes pratiques que j&#8217;avais ratées comme l&#8217;utilisation de labels aux directives <code><strong>#endregion</strong></code></li>
</ul>
<p>J&#8217;ai donc beaucoup appris à la lecture de ce livre, des choses plus ou moins importantes certes, mais toute connaissance est bonne à prendre quand on recherche l&#8217;expertise.</p>
<h1>Conclusion</h1>
<p>Comme vous l&#8217;avez constaté &#8220;<strong>MCSD Certification Toolkit (Exam 70-483): Programming in C#</strong>&#8221; est un livre très inégal.<br />
Ce que je ne comprends pas c&#8217;est pourquoi la version électronique a toujours autant d&#8217;erreurs malgré les réactions offusquées, et souvent un peu disproportionnées, des lecteurs déçus.</p>
<p><strong>Donc devriez-vous lire ce livre ?</strong><br />
Si vous passez la certification 70-483 la réponse est un &#8220;oui&#8221; sans détour parce qu&#8217;il résume bien tous les points qu&#8217;il vous faudra connaitre pour réussir la certification et il vous aidera à déterminer où vous êtes un peu faible.<br />
C&#8217;est aussi un choix par défaut, il n&#8217;y a pas vraiment d&#8217;alternatives.</p>
<p>Par contre si vous avez besoin d&#8217;un livre technique pour monter en compétence alors je le déconseille car vous risqueriez d&#8217;apprendre de mauvaises pratiques, et lire un livre en étant suspicieux n&#8217;est pas bon pour la mémorisation puisqu&#8217;on a tendance à ne plus rien croire.</p>
<p>Surtout ne faites pas comme certains lecteurs qui ont arrêté la lecture après les 1ères pages constatant l&#8217;accumulation d&#8217;erreurs, et cela pour deux raisons :<br />
&#8211; la qualité du livre s&#8217;améliore au fil des chapitres et autant j&#8217;ai trouvé énormément d&#8217;erreurs dans le 1er quart, autant vers la fin c&#8217;était beaucoup plus rare, c&#8217;est comme si la 1ère partie sur les bases avait été confiée à un développeur débutant, le milieu à un développeur un peu plus expérimenté et la dernière partie à un développeur confirmé.<br />
&#8211; même dans les portions truffées d&#8217;erreurs il y a des informations importantes voire même des petites pépites.<br />
Donc même si vous êtes considéré comme un expert ce livre vous apportera quelque chose et il serait dommage de faire l&#8217;impasse dessus pour passer la certification.</p>
<p>Ce qui est certains c&#8217;est que ce livre est le résultat d&#8217;un travail énorme qui mérite beaucoup de respect, et il vaut mieux des ressources imparfaites que pas de ressources du tout.</p>
<p><strong>Ma note finale</strong><br />
Noter ce livre est pour moi assez difficile puisque d&#8217;un côté je trouve l&#8217;accumulation d&#8217;erreurs et d&#8217;approximations techniques dommageables pour les lecteurs non avertis qui doivent constituer une bonne partie de l&#8217;audience, mais d&#8217;un autre côté il remplit parfaitement son office de préparation à la certification.</p>
<p>Si c&#8217;était un livre se voulant une référence technique je lui aurais mis 5/10.<br />
Pour un lecteur souhaitant simplement d&#8217;obtenir la certification alors il vaut 9/10.<br />
Par conséquent je lui donne une note de 8/10, soit 4 étoiles sur 5 sur Amazon, parce que j&#8217;ai surpondéré l&#8217;aspect passage de la certification qui est le propos officiel de ce livre qui n&#8217;a pas l&#8217;ambition d&#8217;être une référence technique.</p>
]]></content:encoded>
							<wfw:commentRss>http://pragmateek.com/french-revue-du-livre-mcsd-certification-toolkit-exam-70-483-programming-in-c/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
							</item>
	</channel>
</rss>
