<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://blogs.msdn.com/utility/FeedStylesheets/rss.xsl" media="screen"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:wfw="http://wellformedweb.org/CommentAPI/"><channel><title>jaredpar's WebLog : Type Inference</title><link>http://blogs.msdn.com/jaredpar/archive/tags/Type+Inference/default.aspx</link><description>Tags: Type Inference</description><dc:language>en-US</dc:language><generator>CommunityServer 2.1 SP1 (Build: 61025.2)</generator><item><title>Making F# type inference friendly for C#</title><link>http://blogs.msdn.com/jaredpar/archive/2009/12/15/making-f-type-inference-friendly-for-c.aspx</link><pubDate>Tue, 15 Dec 2009 19:53:08 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9937228</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>2</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/9937228.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=9937228</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=9937228</wfw:comment><description>&lt;p&gt;One of my current hobby projects, &lt;a href="http://blogs.msdn.com/jaredpar/archive/2009/12/14/vsvim-update-released-version-0-5-4.aspx"&gt;VsVim&lt;/a&gt;, requires me to make a lot of calls between F# and C# projects.&amp;#160; The core Vim engine is a pure F# solution based on Visual Studio’s new editor.&amp;#160; It additionally has a small hosting layer and a large test bed both written in C#.&amp;#160; &lt;/p&gt;  &lt;p&gt;When working with the exposed core Vim engine API, I’ve found a number of generated F# constructs which are not easily accessible from C#.&amp;#160; The problem stems from the manner in which native F# types are exposed.&amp;#160; Many of them are generic and&amp;#160; lack type inference friendly helper methods that force awkward usage patterns in C#.&amp;#160; Most painful is the FSharpOption&amp;lt;T&amp;gt; type because it’s a type I frequently expose in APIs.&amp;#160; &lt;/p&gt;  &lt;p&gt;FSharpOption&amp;lt;T&amp;gt; is the exposed type for the native F# &lt;a href="http://msdn.microsoft.com/en-us/library/dd233245(VS.100).aspx"&gt;option&lt;/a&gt; construct representing a value which may or may not be present. It’s similar to C#’s nullable type except that it applies to all types of values.&amp;#160; The primary operations you want to do with an FSharpOption&amp;lt;T&amp;gt; are &lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;Create an option with a value &lt;/li&gt;    &lt;li&gt;Create an option without a value &lt;/li&gt;    &lt;li&gt;Determine if it has a value &lt;/li&gt;    &lt;li&gt;Determine if it does not have a value &lt;/li&gt;    &lt;li&gt;Access the value &lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;In F# using an option is an inherent part of the language and the hence the resulting code is very elegant. &lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;let &lt;/span&gt;OptionExample = 
    &lt;span style="color: blue"&gt;let &lt;/span&gt;optionWithValue = Some(&lt;span style="color: brown"&gt;42&lt;/span&gt;)
    &lt;span style="color: blue"&gt;let &lt;/span&gt;optionWithoutValue = None
    &lt;span style="color: blue"&gt;let &lt;/span&gt;isSome = Option.isSome optionWithValue
    &lt;span style="color: blue"&gt;let &lt;/span&gt;isNone = Option.isNone optionWithoutValue
    Option.get optionWithValue&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Unfortunately the equivalent C# code is not nearly so nice.&amp;#160; &lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;static int &lt;/span&gt;OptionExample() {
    &lt;span style="color: blue"&gt;var &lt;/span&gt;optionWithValue = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;FSharpOption&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt;(&lt;span style="color: brown"&gt;42&lt;/span&gt;);
    &lt;span style="color: blue"&gt;var &lt;/span&gt;optionWithoutValue = &lt;span style="color: #2b91af"&gt;FSharpOption&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt;.None;
    &lt;span style="color: blue"&gt;var &lt;/span&gt;isSome = &lt;span style="color: #2b91af"&gt;FSharpOption&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt;.get_IsSome(optionWithValue);
    &lt;span style="color: blue"&gt;var &lt;/span&gt;isNone = &lt;span style="color: #2b91af"&gt;FSharpOption&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt;.get_IsNone(optionWithValue);
    return optionWithValue.Value;
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Too many explicit types!!!&amp;#160; Using any explicit type with F# related code just feels wrong.&amp;#160; &lt;/p&gt;

&lt;p&gt;In C#, and most other .Net languages, 4 out of the 5 operations you want to do on FSharpOption require an explicit type parameter.&amp;#160; This resulting code is a bit tedious with a simple type like int but once you get to more complex generics it can get extremely verbose.&amp;#160; In the case of anonymous types, it’s simply not possible to use the FSharpOption&amp;lt;T&amp;gt; without a few wrappers.&amp;#160; &lt;/p&gt;

&lt;p&gt;Luckily most of these can be solved by using the familiar pattern of using a non-generic class with static generic methods.&amp;#160; These allow C# users to take advantage of the languages type inference capabilities to reduce the verbosity of the code.&amp;#160; &lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public static class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;FSharpOption &lt;/span&gt;{
    &lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;FSharpOption&lt;/span&gt;&amp;lt;T&amp;gt; Create&amp;lt;T&amp;gt;(T value) {
        &lt;span style="color: blue"&gt;return new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;FSharpOption&lt;/span&gt;&amp;lt;T&amp;gt;(value);
    }
    &lt;span style="color: blue"&gt;public static bool &lt;/span&gt;IsSome&amp;lt;T&amp;gt;(&lt;span style="color: blue"&gt;this &lt;/span&gt;&lt;span style="color: #2b91af"&gt;FSharpOption&lt;/span&gt;&amp;lt;T&amp;gt; opt) {
        &lt;span style="color: blue"&gt;return &lt;/span&gt;&lt;span style="color: #2b91af"&gt;FSharpOption&lt;/span&gt;&amp;lt;T&amp;gt;.get_IsSome(opt);
    }
    &lt;span style="color: blue"&gt;public static bool &lt;/span&gt;IsNone&amp;lt;T&amp;gt;(&lt;span style="color: blue"&gt;this &lt;/span&gt;&lt;span style="color: #2b91af"&gt;FSharpOption&lt;/span&gt;&amp;lt;T&amp;gt; opt) {
        &lt;span style="color: blue"&gt;return &lt;/span&gt;&lt;span style="color: #2b91af"&gt;FSharpOption&lt;/span&gt;&amp;lt;T&amp;gt;.get_IsNone(opt);
    }
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Now we can rewrite the original sample a bit cleaner &lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;static int &lt;/span&gt;OptionExample() {
    &lt;span style="color: blue"&gt;var &lt;/span&gt;optionWithValue = &lt;span style="color: #2b91af"&gt;FSharpOption&lt;/span&gt;.Create(&lt;span style="color: brown"&gt;42&lt;/span&gt;);
    &lt;span style="color: blue"&gt;var &lt;/span&gt;optionWithoutValue = &lt;span style="color: #2b91af"&gt;FSharpOption&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt;.None;
    &lt;span style="color: blue"&gt;var &lt;/span&gt;isSome = optionWithValue.IsSome();
    &lt;span style="color: blue"&gt;var &lt;/span&gt;isNone = optionWithoutValue.IsNone();
    &lt;span style="color: blue"&gt;return &lt;/span&gt;optionWithValue.Value;
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Notice we still haven’t fixed the None case.&amp;#160; Fixing this is a beyond the scope of what I want to write here but it is possible in certain scenarios.&amp;#160; You can take a look at how in one of my previous blog articles: &lt;a href="http://blogs.msdn.com/jaredpar/archive/2008/10/06/functional-c-providing-an-option.aspx"&gt;Function C# Providing an Option&lt;/a&gt;.&amp;#160; &lt;/p&gt;

&lt;p&gt;This pattern is not just limited to the FSharpOption class but can be applied to many of the generic constructs F# exports to wrap their native types.&amp;#160; In particular FSharpFunc&amp;lt;T,Result&amp;gt; and the various FSharpChoice&amp;lt;&amp;gt; types can be made a bit friendlier with a few wrappers.&amp;#160; &lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9937228" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Type+Inference/default.aspx">Type Inference</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/F_2300_/default.aspx">F#</category></item><item><title>Using F# Discriminated Unions in C# (Beta2)</title><link>http://blogs.msdn.com/jaredpar/archive/2009/10/27/using-f-discriminated-unions-in-c-beta2.aspx</link><pubDate>Tue, 27 Oct 2009 12:00:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9913363</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>5</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/9913363.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=9913363</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=9913363</wfw:comment><description>&lt;p&gt;While updating my VsVim editor extensions for Beta2 [1] I got hit by a change in the way F# exposed discriminated unions in metadata.&amp;#160; My extension consists of a core F# component with a corresponding set of unit tests written in C#.&amp;#160; It’s mostly API level testing and as such I use a lot of F# generated types in my C# test assembly.&lt;/p&gt;  &lt;p&gt;In Beta1 all information which could be extracted from a discriminated type union was immediately available on the value.&amp;#160; The underlying type presentation was less than desirable but these details were hidden by type inference and the very accessible API.&amp;#160;&amp;#160; The type wasn’t perfect because given a particular instance only the subset of the properties relevant to the union value type were valid.&amp;#160; All others threw exceptions.&amp;#160; But the code use of these methods and properties flowed very well.&amp;#160;&amp;#160; &lt;/p&gt;  &lt;p&gt;For instance take the following F# definition&lt;/p&gt;  &lt;pre class="code"&gt;&lt;span style="color: blue"&gt;type &lt;/span&gt;ActionKind =
    | Mouse = &lt;span style="color: brown"&gt;1
    &lt;/span&gt;| Keyboard = &lt;span style="color: brown"&gt;2

&lt;/span&gt;&lt;span style="color: blue"&gt;type &lt;/span&gt;ActionResult =
    | Complete &lt;span style="color: blue"&gt;of &lt;/span&gt;(ActionKind * int)
    | Error &lt;span style="color: blue"&gt;of &lt;/span&gt;string
    | NeedMore &lt;span style="color: blue"&gt;of &lt;/span&gt;(char &lt;span style="color: blue"&gt;-&amp;gt; &lt;/span&gt;ActionResult)&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The use case in C# was quite simple&lt;/p&gt;

&lt;pre class="code"&gt;[&lt;span style="color: #2b91af"&gt;TestMethod&lt;/span&gt;]
&lt;span style="color: blue"&gt;public void &lt;/span&gt;TestActionBeta1(){
    &lt;span style="color: blue"&gt;var &lt;/span&gt;res = GetResult();
    &lt;span style="color: #2b91af"&gt;Assert&lt;/span&gt;.IsTrue(res.IsComplete());
    &lt;span style="color: #2b91af"&gt;Assert&lt;/span&gt;.AreEqual(&lt;span style="color: #2b91af"&gt;ActionKind&lt;/span&gt;.Mouse, res.Complete1.Item1);
    &lt;span style="color: #2b91af"&gt;Assert&lt;/span&gt;.AreEqual(&lt;span style="color: brown"&gt;42&lt;/span&gt;, res.Complete1.Item2);
}&lt;/pre&gt;

&lt;p&gt;Notice how no type information is necessary and the code flows quite naturally.&amp;#160; C# type inference works great here and allows me to do what I need to do without fussing around with little stuff.&amp;#160; The type in this case is a detail I don’t need to know about.&amp;#160; It simply adds no value.&amp;#160; &lt;/p&gt;

&lt;p&gt;Discriminated Unions in Beta2 changed substantially in this area.&amp;#160; Instead of generating the set of all values on the exposed type, there is now an inner type generated for every discriminated union value and the properties relevant to that union value are stored on the inner type.&amp;#160; The outer type now contains only properties to determine which type of value it is (certainly an upgrade from methods!) [2]&lt;/p&gt;

&lt;p&gt;For instance in the case of ActionResult there are 3 generated inner classes: Complete, Error and NeedMore.&amp;#160; Each one contains a single property Item which contains the associated value(s).&amp;#160; This means to get to the value portion a cast to the inner type must be inserted!&amp;#160; &lt;/p&gt;

&lt;p&gt;Lets take a a look at how the above test code has to change to deal with the Beta2 generation of ActionResult.&amp;#160; &lt;/p&gt;

&lt;pre class="code"&gt;[&lt;span style="color: #2b91af"&gt;TestMethod&lt;/span&gt;]
&lt;span style="color: blue"&gt;public void &lt;/span&gt;TestActionBeta2() {
    &lt;span style="color: blue"&gt;var &lt;/span&gt;res = GetResult();
    &lt;span style="color: #2b91af"&gt;Assert&lt;/span&gt;.IsTrue(res.IsComplete);
    &lt;span style="color: #2b91af"&gt;Assert&lt;/span&gt;.AreEqual(&lt;span style="color: #2b91af"&gt;ActionKind&lt;/span&gt;.Mouse, ((&lt;span style="color: #2b91af"&gt;ActionResult&lt;/span&gt;.&lt;span style="color: #2b91af"&gt;Complete&lt;/span&gt;)res).Item.Item1);
    &lt;span style="color: #2b91af"&gt;Assert&lt;/span&gt;.AreEqual(&lt;span style="color: brown"&gt;42&lt;/span&gt;, ((&lt;span style="color: #2b91af"&gt;ActionResult&lt;/span&gt;.&lt;span style="color: #2b91af"&gt;Complete&lt;/span&gt;)res).Item.Item2);
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;Notice the explicit casts which must be added to access the values.&amp;#160; This makes it impossible to rely soley on C# type inference.&amp;#160; I must now understand the underlying type structure of discriminated unions in order to use them.&amp;#160; This extra cast adds no real value to my code.&amp;#160; &lt;/p&gt;

&lt;p&gt;My C# test assembly has literally hundreds of test cases which use this pattern on F# types.&amp;#160; I didn’t know the return type of every method and found myself hitting “Goto Def” on a lot of “var” instances to discover the static type, going back to the original file and inserting the cast.&amp;#160; It was a tedious and slow process.&lt;/p&gt;

&lt;p&gt;Eventually I settled on a different solution.&amp;#160; For every type I exposed in F# I added a set of extension methods in the form of AsXXX where XXX represented the name of the generated inner types.&amp;#160;&amp;#160; For example&lt;/p&gt;

&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ActionResult&lt;/span&gt;.&lt;span style="color: #2b91af"&gt;Complete &lt;/span&gt;AsComplete(&lt;span style="color: blue"&gt;this &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ActionResult &lt;/span&gt;res) {
    &lt;span style="color: blue"&gt;return &lt;/span&gt;(&lt;span style="color: #2b91af"&gt;ActionResult&lt;/span&gt;.&lt;span style="color: #2b91af"&gt;Complete&lt;/span&gt;)res;
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;The advantage of this approach is 2 fold &lt;/p&gt;

&lt;ol&gt;
  &lt;li&gt;Removes the need to explicitly name types in code and hence gets back the advantages of type inference&lt;/li&gt;

  &lt;li&gt;I can now use . on any of the values and let Intellisense help me find the appropriate method to use&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This extension method allows me to get closer to the Beta1 style code &lt;/p&gt;

&lt;pre class="code"&gt;[&lt;span style="color: #2b91af"&gt;TestMethod&lt;/span&gt;]
&lt;span style="color: blue"&gt;public void &lt;/span&gt;TestActionBeta2() {
    &lt;span style="color: blue"&gt;var &lt;/span&gt;res = GetResult();
    &lt;span style="color: #2b91af"&gt;Assert&lt;/span&gt;.IsTrue(res.IsComplete);
    &lt;span style="color: #2b91af"&gt;Assert&lt;/span&gt;.AreEqual(&lt;span style="color: #2b91af"&gt;ActionKind&lt;/span&gt;.Mouse, res.AsComplete().Item.Item1);
    &lt;span style="color: #2b91af"&gt;Assert&lt;/span&gt;.AreEqual(&lt;span style="color: brown"&gt;42&lt;/span&gt;, res.AsComplete().Item.Item2);
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;

&lt;p&gt;With these methods and a quick series of Find / Replace calls, I was back in business.&amp;#160; &lt;/p&gt;

&lt;p&gt;[1] It’s coming I promise!&amp;#160; &lt;/p&gt;

&lt;p&gt;[2] It also contains a handy set of factory methods for generating values but it’s not relevant to this discussion.&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9913363" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Extension+Methods/default.aspx">Extension Methods</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Type+Inference/default.aspx">Type Inference</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/F_2300_/default.aspx">F#</category></item><item><title>When to use Type Inference</title><link>http://blogs.msdn.com/jaredpar/archive/2008/09/09/when-to-use-type-inference.aspx</link><pubDate>Tue, 09 Sep 2008 15:00:10 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8931894</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>27</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/8931894.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=8931894</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=8931894</wfw:comment><description>&lt;p&gt;Occasionally the debate will come as to when it's OK to use type inference in order to declare a variable.&amp;#160; There appear to be three groups in this debate.&lt;/p&gt;  &lt;ol&gt;   &lt;li&gt;Whenever it's possible&lt;/li&gt;    &lt;li&gt;Only when it's absolutely clear what the type is &lt;/li&gt;    &lt;li&gt;Never, type inference is evil&lt;/li&gt; &lt;/ol&gt;  &lt;p&gt;I fall into camp #1 and here are my reasons&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;It does not reduce type safety.&amp;#160; This doesn't allow for any late binding, type unsafe functions or the like.&amp;#160; It simply lets the compiler chose the type for you.&lt;/li&gt;    &lt;li&gt;It will actually increase type safety in your code.&amp;#160; The best example of this is the foreach statement on non-generic IEnumerable instances.&amp;#160; These foreach statements are all technically unsafe because the compiler must do a cast of the Current member under the hood.&amp;#160; This declaration looks no different than the type safe generic version of IEnumerable.&amp;#160; Using var will force you to write an explicit cast.&amp;#160;&amp;#160; &lt;/li&gt; &lt;/ul&gt;  &lt;blockquote&gt;   &lt;p&gt;foreach (SomeType cur in col)&lt;/p&gt; &lt;/blockquote&gt;  &lt;blockquote&gt;   &lt;p&gt;foreach ( var cur in col.Cast&amp;lt;SomeType&amp;gt;())&lt;/p&gt; &lt;/blockquote&gt;  &lt;ul&gt;   &lt;li&gt;Maintains the principles of DRY.&amp;#160; This is mostly true for cases where you have an explicit constructor on the RHS.&lt;/li&gt;    &lt;li&gt;For some types, this is a requirement in order to use the type (anonymous types for instance).&amp;#160; I'm a big fan of consistency and since I must have some instances use type inference, I'd like to use them everywhere.&amp;#160; &lt;/li&gt;    &lt;li&gt;Makes refactoring easier.&amp;#160; I re-factor, a lot.&amp;#160; I constantly split up or rename types.&amp;#160; Often in such a way that refactoring tools don't fixup all of the problems.&amp;#160; With var declarations I don't have to worry because they just properly infer their new type and happily chug along.&amp;#160; For explicit type cases I have to manually update all of the type names.&amp;#160; &lt;/li&gt;    &lt;li&gt;Less typing with no loss of functionality.&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;The best argument I've heard against type inference is that it reduces readability since you can't look at a variable and know it's type.&amp;#160; True, but just hover over the declaration and the IDE will display the type.&amp;#160; Yes this is not possible with a non-IDE editor but how often do you use one? &lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8931894" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Type+Inference/default.aspx">Type Inference</category></item><item><title>Switching on Types</title><link>http://blogs.msdn.com/jaredpar/archive/2008/05/16/switching-on-types.aspx</link><pubDate>Fri, 16 May 2008 15:00:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8506222</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>9</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/8506222.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=8506222</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=8506222</wfw:comment><description>&lt;P&gt;One action I find frustrating in C# is where a particular action needs to be taken based off of the type of a particular object.&amp;nbsp; Ideally I would like to solve this with a switch statement but switch statements only support constant expressions in C# so no luck there.&amp;nbsp; Previously I've had to resort to ugly looking code like the following.&amp;nbsp; &lt;/P&gt;&lt;PRE class=code&gt;&lt;SPAN style="COLOR: #2b91af"&gt;Type &lt;/SPAN&gt;t = sender.GetType();
&lt;SPAN style="COLOR: blue"&gt;if &lt;/SPAN&gt;(t == &lt;SPAN style="COLOR: blue"&gt;typeof&lt;/SPAN&gt;(&lt;SPAN style="COLOR: #2b91af"&gt;Button&lt;/SPAN&gt;)) {
    &lt;SPAN style="COLOR: blue"&gt;var &lt;/SPAN&gt;realObj = (&lt;SPAN style="COLOR: #2b91af"&gt;Button&lt;/SPAN&gt;)sender;
    &lt;SPAN style="COLOR: green"&gt;// Do Something
&lt;/SPAN&gt;}
&lt;SPAN style="COLOR: blue"&gt;else if &lt;/SPAN&gt;(t == &lt;SPAN style="COLOR: blue"&gt;typeof&lt;/SPAN&gt;(&lt;SPAN style="COLOR: #2b91af"&gt;CheckBox&lt;/SPAN&gt;)) {
    &lt;SPAN style="COLOR: blue"&gt;var &lt;/SPAN&gt;realObj = (&lt;SPAN style="COLOR: #2b91af"&gt;CheckBox&lt;/SPAN&gt;)sender;
    &lt;SPAN style="COLOR: green"&gt;// Do something else
&lt;/SPAN&gt;}
&lt;SPAN style="COLOR: blue"&gt;else &lt;/SPAN&gt;{
    &lt;SPAN style="COLOR: green"&gt;// Default action
&lt;/SPAN&gt;}&lt;/PRE&gt;&lt;A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/A&gt;
&lt;P&gt;Yes I realize this isn't the ugliest code but it seems less elegant to me over a standard switch statement and I find the casting tedious.&amp;nbsp; Especially since it requires you to write every type twice.&amp;nbsp; &lt;/P&gt;
&lt;P&gt;What I want to say is "Given this type, execute this block of code."&amp;nbsp; So I decided to run with that this afternoon.&amp;nbsp; Lambdas will serve nicely for the block of code and using type inference will allow us to avoid writing every type out twice.&amp;nbsp; What I ended up with was a class called TypeSwitch with 3 main methods (see bottom of post for full code).&lt;/P&gt;
&lt;UL&gt;
&lt;LI&gt;Do - Entry point where switching begins &lt;/LI&gt;
&lt;LI&gt;Case - Several overloads which take a generic type argument and an Action&amp;lt;T&amp;gt; to run for the object &lt;/LI&gt;
&lt;LI&gt;Default - Optional default action.&amp;nbsp; &lt;/LI&gt;&lt;/UL&gt;
&lt;P&gt;I wrote a quick winforms app to test out the solution.&amp;nbsp; I dropped some random controls on a from and bound the MouseHover event for all of them to a single method.&amp;nbsp; I can now use the following code to print out different messages based on the type.&amp;nbsp; &lt;/P&gt;&lt;PRE class=code&gt;&lt;SPAN style="COLOR: #2b91af"&gt;TypeSwitch&lt;/SPAN&gt;.Do(
    sender,
    &lt;SPAN style="COLOR: #2b91af"&gt;TypeSwitch&lt;/SPAN&gt;.Case&amp;lt;&lt;SPAN style="COLOR: #2b91af"&gt;Button&lt;/SPAN&gt;&amp;gt;(() =&amp;gt; textBox1.Text = &lt;SPAN style="COLOR: #a31515"&gt;"Hit a Button"&lt;/SPAN&gt;),
    &lt;SPAN style="COLOR: #2b91af"&gt;TypeSwitch&lt;/SPAN&gt;.Case&amp;lt;&lt;SPAN style="COLOR: #2b91af"&gt;CheckBox&lt;/SPAN&gt;&amp;gt;(x =&amp;gt; textBox1.Text = &lt;SPAN style="COLOR: #a31515"&gt;"Checkbox is " &lt;/SPAN&gt;+ x.Checked),
    &lt;SPAN style="COLOR: #2b91af"&gt;TypeSwitch&lt;/SPAN&gt;.Default(() =&amp;gt; textBox1.Text = &lt;SPAN style="COLOR: #a31515"&gt;"Not sure what is hovered over"&lt;/SPAN&gt;));&lt;/PRE&gt;&lt;A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/A&gt;&lt;PRE class=code&gt;&lt;SPAN style="COLOR: blue"&gt;&lt;/SPAN&gt;&lt;/PRE&gt;
&lt;P&gt;Notice that for check box I was able to access CheckBox properties in a strongly typed fashion.&amp;nbsp; The underlying case code will optionally pass the first argument to the lambda expression strongly typed to the value specified as the generic argument.&amp;nbsp; &lt;/P&gt;
&lt;P&gt;There are a couple of faults with this approach including Default being anywhere in the list but it was a fun experiment and works well.&amp;nbsp; &lt;/P&gt;
&lt;P&gt;TypeSwitch code.&lt;/P&gt;&lt;PRE class=code&gt;&lt;SPAN style="COLOR: blue"&gt;static class &lt;/SPAN&gt;&lt;SPAN style="COLOR: #2b91af"&gt;TypeSwitch &lt;/SPAN&gt;{
    &lt;SPAN style="COLOR: blue"&gt;public class &lt;/SPAN&gt;&lt;SPAN style="COLOR: #2b91af"&gt;CaseInfo &lt;/SPAN&gt;{
        &lt;SPAN style="COLOR: blue"&gt;public bool &lt;/SPAN&gt;IsDefault { &lt;SPAN style="COLOR: blue"&gt;get&lt;/SPAN&gt;; &lt;SPAN style="COLOR: blue"&gt;set&lt;/SPAN&gt;; }
        &lt;SPAN style="COLOR: blue"&gt;public &lt;/SPAN&gt;&lt;SPAN style="COLOR: #2b91af"&gt;Type &lt;/SPAN&gt;Target { &lt;SPAN style="COLOR: blue"&gt;get&lt;/SPAN&gt;; &lt;SPAN style="COLOR: blue"&gt;set&lt;/SPAN&gt;; }
        &lt;SPAN style="COLOR: blue"&gt;public &lt;/SPAN&gt;&lt;SPAN style="COLOR: #2b91af"&gt;Action&lt;/SPAN&gt;&amp;lt;&lt;SPAN style="COLOR: blue"&gt;object&lt;/SPAN&gt;&amp;gt; Action { &lt;SPAN style="COLOR: blue"&gt;get&lt;/SPAN&gt;; &lt;SPAN style="COLOR: blue"&gt;set&lt;/SPAN&gt;; }
    }

    &lt;SPAN style="COLOR: blue"&gt;public static void &lt;/SPAN&gt;Do(&lt;SPAN style="COLOR: blue"&gt;object &lt;/SPAN&gt;source, &lt;SPAN style="COLOR: blue"&gt;params &lt;/SPAN&gt;&lt;SPAN style="COLOR: #2b91af"&gt;CaseInfo&lt;/SPAN&gt;[] cases) {
        &lt;SPAN style="COLOR: blue"&gt;var &lt;/SPAN&gt;type = source.GetType();
        &lt;SPAN style="COLOR: blue"&gt;foreach &lt;/SPAN&gt;(&lt;SPAN style="COLOR: blue"&gt;var &lt;/SPAN&gt;entry &lt;SPAN style="COLOR: blue"&gt;in &lt;/SPAN&gt;cases) {
            &lt;SPAN style="COLOR: blue"&gt;if &lt;/SPAN&gt;(entry.IsDefault || type == entry.Target) {
                entry.Action(source);
                &lt;SPAN style="COLOR: blue"&gt;break&lt;/SPAN&gt;;
            }
        }
    }

    &lt;SPAN style="COLOR: blue"&gt;public static &lt;/SPAN&gt;&lt;SPAN style="COLOR: #2b91af"&gt;CaseInfo &lt;/SPAN&gt;Case&amp;lt;T&amp;gt;(&lt;SPAN style="COLOR: #2b91af"&gt;Action &lt;/SPAN&gt;action) {
        &lt;SPAN style="COLOR: blue"&gt;return new &lt;/SPAN&gt;&lt;SPAN style="COLOR: #2b91af"&gt;CaseInfo&lt;/SPAN&gt;() {
            Action = x =&amp;gt; action(),
            Target = &lt;SPAN style="COLOR: blue"&gt;typeof&lt;/SPAN&gt;(T)
        };
    }

    &lt;SPAN style="COLOR: blue"&gt;public static &lt;/SPAN&gt;&lt;SPAN style="COLOR: #2b91af"&gt;CaseInfo &lt;/SPAN&gt;Case&amp;lt;T&amp;gt;(&lt;SPAN style="COLOR: #2b91af"&gt;Action&lt;/SPAN&gt;&amp;lt;T&amp;gt; action) {
        &lt;SPAN style="COLOR: blue"&gt;return new &lt;/SPAN&gt;&lt;SPAN style="COLOR: #2b91af"&gt;CaseInfo&lt;/SPAN&gt;() {
            Action = (x) =&amp;gt; action((T)x),
            Target = &lt;SPAN style="COLOR: blue"&gt;typeof&lt;/SPAN&gt;(T)
        };
    }

    &lt;SPAN style="COLOR: blue"&gt;public static &lt;/SPAN&gt;&lt;SPAN style="COLOR: #2b91af"&gt;CaseInfo &lt;/SPAN&gt;Default(&lt;SPAN style="COLOR: #2b91af"&gt;Action &lt;/SPAN&gt;action) {
        &lt;SPAN style="COLOR: blue"&gt;return new &lt;/SPAN&gt;&lt;SPAN style="COLOR: #2b91af"&gt;CaseInfo&lt;/SPAN&gt;() {
            Action = x =&amp;gt; action(),
            IsDefault = &lt;SPAN style="COLOR: blue"&gt;true
        &lt;/SPAN&gt;};
    }
}&lt;/PRE&gt;&lt;A href="http://11011.net/software/vspaste" mce_href="http://11011.net/software/vspaste"&gt;&lt;/A&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8506222" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Patterns/default.aspx">Patterns</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Lambda/default.aspx">Lambda</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Type+Inference/default.aspx">Type Inference</category></item><item><title>Design Guidelines: Provide type inference friendly Create function for generic objects</title><link>http://blogs.msdn.com/jaredpar/archive/2008/04/11/design-guidelines-provide-type-inference-friendly-create-function-for-generic-objects.aspx</link><pubDate>Fri, 11 Apr 2008 15:24:50 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8363462</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>3</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/8363462.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=8363462</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=8363462</wfw:comment><description>&lt;p&gt;Really this guideline is a bit longer but putting it all in a blog title seemed a bit too much.&amp;#160; The full guideline should read: &amp;quot;If a generic class constructor arguments contain types of all generic parameters, provide a static method named Create on a static class of the same class name as the generic class which takes the same arguments and calls the constructor.&amp;quot;&amp;#160; Quite a mouth full.&amp;#160; &lt;/p&gt;  &lt;p&gt;Lets look at a specific example with &lt;a href="http://blogs.msdn.com/jaredpar/archive/2008/01/27/tuples-part-8-finishing-up.aspx"&gt;Tuples&lt;/a&gt;.&amp;#160; Tuples are generic with respect to the values they are representing.&amp;#160; Without any type inference help we would have to write the following code to create a simple tuple. &lt;/p&gt;  &lt;pre class="code"&gt;            &lt;span style="color: rgb(0,0,255)"&gt;var&lt;/span&gt; tuple = &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;Tuple&lt;/span&gt;&amp;lt;&lt;span style="color: rgb(0,0,255)"&gt;int&lt;/span&gt;, &lt;span style="color: rgb(0,0,255)"&gt;string&lt;/span&gt;&amp;gt;(5, &lt;span style="color: rgb(163,21,21)"&gt;&amp;quot;astring&amp;quot;&lt;/span&gt;);&lt;/pre&gt;

&lt;p&gt;Not too bad because we are using simple types.&amp;#160; But what happens when we are using really long type names?&amp;#160; &lt;/p&gt;

&lt;pre class="code"&gt;            &lt;span style="color: rgb(0,0,255)"&gt;var&lt;/span&gt; tuple2 = &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;Tuple&lt;/span&gt;&amp;lt;&lt;span style="color: rgb(0,0,255)"&gt;string&lt;/span&gt;,&lt;span style="color: rgb(43,145,175)"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color: rgb(0,0,255)"&gt;string&lt;/span&gt;, &lt;span style="color: rgb(43,145,175)"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: rgb(0,0,255)"&gt;int&lt;/span&gt;&amp;gt;&amp;gt;&amp;gt;(val1, val2);&lt;/pre&gt;

&lt;p&gt;As we can see, the code is getting quite a bit uglier.&amp;#160; This pattern is in fact not maintainable once we start using un-namable types such as anonymous types or generics of anonymous types.&amp;#160; &lt;/p&gt;

&lt;p&gt;The problem here is we are not leveraging the compilers type inference capabilities.&amp;#160; The compiler can easily infer the types of a tuple argument and hence create a tuple.&amp;#160; We just need to provide a mechanism to do so.&amp;#160; The best way is to define a static method on a static class with the same name as the generic.&amp;#160; Lets call this method Create.&lt;/p&gt;

&lt;pre class="code"&gt;    &lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;static&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;class&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;Tuple&lt;/span&gt; {
        &lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;static&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;Tuple&lt;/span&gt;&amp;lt;TA, TB&amp;gt; Create&amp;lt;TA, TB&amp;gt;(TA valueA, TB valueB) { 
            &lt;span style="color: rgb(0,0,255)"&gt;return&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;Tuple&lt;/span&gt;&amp;lt;TA, TB&amp;gt;(valueA, valueB); 
        }
    }&lt;/pre&gt;

&lt;p&gt;The method Tuple.Create still has two generic parameters.&amp;#160; However since we are providing a set of values which contain types for every generic parameter, the compiler can infer the generic arguments.&amp;#160; Now we can create a Tuple without specifying any generic arguments.&amp;#160; Because no types are specified this will work with any value in the code including un-namable types.&amp;#160; &lt;/p&gt;

&lt;pre class="code"&gt;            &lt;span style="color: rgb(0,0,255)"&gt;var&lt;/span&gt; tuple = &lt;span style="color: rgb(43,145,175)"&gt;Tuple&lt;/span&gt;.Create(6, &lt;span style="color: rgb(163,21,21)"&gt;&amp;quot;astring&amp;quot;&lt;/span&gt;);
            &lt;span style="color: rgb(0,0,255)"&gt;var&lt;/span&gt; tuple2 = &lt;span style="color: rgb(43,145,175)"&gt;Tuple&lt;/span&gt;.Create(6, &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; { name = &lt;span style="color: rgb(163,21,21)"&gt;&amp;quot;aname&amp;quot;&lt;/span&gt;, value = 42 });&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8363462" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Generics/default.aspx">Generics</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Patterns/default.aspx">Patterns</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Type+Inference/default.aspx">Type Inference</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/API+Design/default.aspx">API Design</category></item><item><title>Tuples Part 3: Type Inference Friendly Constructor</title><link>http://blogs.msdn.com/jaredpar/archive/2008/01/07/tuples-part-3-type-inference-friendly-constructor.aspx</link><pubDate>Mon, 07 Jan 2008 19:38:11 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:7017156</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>1</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/7017156.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=7017156</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=7017156</wfw:comment><description>&lt;p&gt;&lt;a href="http://blogs.msdn.com/jaredpar/archive/2008/01/04/tuples-part-2-basic-structure.aspx"&gt;Last time&lt;/a&gt; we were left with a constructor that required us to explicitly specify generic parameters.&amp;nbsp; This is not always easy or possible.&amp;nbsp; We'll now alter the script to generate a constructor which utilizes type inference to create a Tuple.&amp;nbsp; In addition, all tuples will use the same overloaded method making the creation uniform.&amp;nbsp; &lt;/p&gt; &lt;p&gt;The best way to use type inference to create a generic argument is through static methods.&amp;nbsp; In C# and VB it's legal to define a non-generic class with the same name as a generic class.&amp;nbsp; I tend to create a non-generic class with a static Create method that takes advantage of type inference.&amp;nbsp; For tuples the method will look like the following. &lt;/p&gt;&lt;pre class="code"&gt;&lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;partial&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;class&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;Tuple
&lt;/span&gt;{
    &lt;span style="color: rgb(0,0,255)"&gt;public&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;static&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;Tuple&lt;/span&gt;&amp;lt;TA&amp;gt; Create&amp;lt;TA&amp;gt;(TA a)
    { 
        &lt;span style="color: rgb(0,0,255)"&gt;return&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;Tuple&lt;/span&gt;&amp;lt;TA&amp;gt;(a); 
    }
}&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;This allows us to write the following code.&amp;nbsp; &lt;/p&gt;&lt;pre class="code"&gt;            &lt;span style="color: rgb(0,0,255)"&gt;var&lt;/span&gt; tuple = &lt;span style="color: rgb(43,145,175)"&gt;Tuple&lt;/span&gt;.Create(&lt;span style="color: rgb(163,21,21)"&gt;"foo"&lt;/span&gt;);&lt;/pre&gt;
&lt;p&gt;Partial classes are used because we will be generating one per Tuple class that we create.&amp;nbsp; It's just easier to script it this way.&amp;nbsp; &lt;/p&gt;
&lt;p&gt;The method is very straight forward.&amp;nbsp; We need one new additional string for the arguments to the constructor.&amp;nbsp; It's created along the same line as the previous strings.&amp;nbsp; &lt;/p&gt;
&lt;p&gt;function script:Gen-InferenceConstructor &lt;br&gt;{ &lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; param ( [int] $count = $(throw "Need a count") ) &lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; $OFS = ',' &lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; $gen = "&amp;lt;" + [string](0..($count-1) | %{ "T"+$upperList[$_] }) + "&amp;gt;"&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; $list = [string](0..$($count-1) | %{ "T{0} {1}" -f $upperList[$_],$lowerList[$_] }) &lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; $argList = [string](0..$($count-1) | %{ $lowerList[$_] }) &lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; "public partial class Tuple {" &lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; "public static Tuple$gen Create$gen($list) { return new Tuple$gen($argList); } " &lt;br&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; "}" &lt;br&gt;} &lt;/p&gt;
&lt;p&gt;Now just add a call to this function in Get-Tuple and the code is now inference friendly.&amp;nbsp; &lt;/p&gt;
&lt;p&gt;Next up is defining an interface for tuples that will allow us to treat a Tuple&amp;lt;2&amp;gt; as a Tuple&amp;lt;1&amp;gt;.&amp;nbsp; Both have an "A" property and should be able to be used in a generic way.&amp;nbsp; &lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=7017156" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/PowerShell/default.aspx">PowerShell</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Type+Inference/default.aspx">Type Inference</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Tuple/default.aspx">Tuple</category></item><item><title>C# Lambda Type Inference</title><link>http://blogs.msdn.com/jaredpar/archive/2007/12/14/c-lambda-type-inference.aspx</link><pubDate>Fri, 14 Dec 2007 20:41:47 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:6771356</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>1</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/6771356.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=6771356</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=6771356</wfw:comment><description>&lt;p&gt;One of the limitations of C# type inference is that you cannot use it to infer the type of a lambda expression.&amp;nbsp; For example, the following code will not compile&lt;/p&gt;&lt;pre class="code"&gt;            &lt;span style="color: rgb(0,0,255)"&gt;var&lt;/span&gt; f = () =&amp;gt; 4;
&lt;/pre&gt;
&lt;p&gt;Normally this is not too much of an issue because you can just explicitly declare the type of the lambda expression. &lt;/p&gt;&lt;pre class="code"&gt;            &lt;span style="color: rgb(43,145,175)"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color: rgb(0,0,255)"&gt;int&lt;/span&gt;&amp;gt; f = () =&amp;gt; 4;&lt;/pre&gt;
&lt;p&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;However, this can be annoying at times.&amp;nbsp; Once you start defining complex lambda expressions the Func/Action declaration can be quite convoluted.&amp;nbsp; Even worse, if your lambda returns an anonymous type, there is no way to declare a Func&amp;lt;&amp;gt; with the anonymous type parameter because you cannot describe it's shape.&amp;nbsp; &lt;/p&gt;&lt;pre class="code"&gt;            Func&amp;lt;???&amp;gt; f = () =&amp;gt; &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; { Name = &lt;span style="color: rgb(163,21,21)"&gt;"foo"&lt;/span&gt; };&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;This is fixable though by using type inference.&amp;nbsp; The method is very similar to &lt;a href="http://blogs.msdn.com/jaredpar/archive/2007/10/01/casting-to-an-anonymous-type.aspx"&gt;other anonymous type type tricks&lt;/a&gt;.&amp;nbsp; While lambda type inference is not supported for variable declaration it is supported for parameters.&amp;nbsp; C# supports return type inference so that can be used to type the variable.&amp;nbsp; &lt;/p&gt;&lt;pre class="code"&gt;        &lt;span style="color: rgb(0,0,255)"&gt;static&lt;/span&gt; &lt;span style="color: rgb(43,145,175)"&gt;Func&lt;/span&gt;&amp;lt;T&amp;gt; Lambda&amp;lt;T&amp;gt;(&lt;span style="color: rgb(43,145,175)"&gt;Func&lt;/span&gt;&amp;lt;T&amp;gt; del)
        {
            &lt;span style="color: rgb(0,0,255)"&gt;return&lt;/span&gt; del;
        }

        &lt;span style="color: rgb(0,0,255)"&gt;static&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;void&lt;/span&gt; Main(&lt;span style="color: rgb(0,0,255)"&gt;string&lt;/span&gt;[] args)
        {
            &lt;span style="color: rgb(0,0,255)"&gt;var&lt;/span&gt; f = Lambda(() =&amp;gt; &lt;span style="color: rgb(0,0,255)"&gt;new&lt;/span&gt; { Name = &lt;span style="color: rgb(163,21,21)"&gt;"foo"&lt;/span&gt; });
        }&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=6771356" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/C_2300_/default.aspx">C#</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Generics/default.aspx">Generics</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Lambda/default.aspx">Lambda</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Type+Inference/default.aspx">Type Inference</category></item><item><title>Type Inference and IEnumerable</title><link>http://blogs.msdn.com/jaredpar/archive/2007/11/26/type-inference-and-ienumerable.aspx</link><pubDate>Tue, 27 Nov 2007 01:32:10 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:6536165</guid><dc:creator>Jared Parsons</dc:creator><slash:comments>2</slash:comments><comments>http://blogs.msdn.com/jaredpar/comments/6536165.aspx</comments><wfw:commentRss>http://blogs.msdn.com/jaredpar/commentrss.aspx?PostID=6536165</wfw:commentRss><wfw:comment>http://blogs.msdn.com/jaredpar/rsscomments.aspx?PostID=6536165</wfw:comment><description>&lt;p&gt;This is somewhat of a follow up on a previous &lt;a href="http://blogs.msdn.com/jaredpar/archive/2007/10/04/ienumerable-and-ienumerable-of-t.aspx"&gt;post&lt;/a&gt; I did on the difference between &lt;a href="http://msdn2.microsoft.com/en-us/library/9eekhta0.aspx"&gt;IEnumerable(Of T)&lt;/a&gt; and the &lt;a href="http://msdn2.microsoft.com/en-us/library/9eekhta0.aspx"&gt;IEnumerable&lt;/a&gt; interfaces.&amp;nbsp; &lt;/p&gt; &lt;p&gt;I've seen several people type in the following code and wonder if there was a fundamental bug in the type inference code.&lt;/p&gt;&lt;pre class="code"&gt;    &lt;span style="color: rgb(0,0,255)"&gt;Private&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Sub&lt;/span&gt; Form1_Load(&lt;span style="color: rgb(0,0,255)"&gt;ByVal&lt;/span&gt; sender &lt;span style="color: rgb(0,0,255)"&gt;As&lt;/span&gt; System.Object, &lt;span style="color: rgb(0,0,255)"&gt;ByVal&lt;/span&gt; e &lt;span style="color: rgb(0,0,255)"&gt;As&lt;/span&gt; System.EventArgs) &lt;span style="color: rgb(0,0,255)"&gt;Handles&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;MyBase&lt;/span&gt;.Load
        &lt;span style="color: rgb(0,0,255)"&gt;For&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Each&lt;/span&gt; cur &lt;span style="color: rgb(0,0,255)"&gt;In&lt;/span&gt; Controls
            cur.Text = &lt;span style="color: rgb(163,21,21)"&gt;"A Value"
&lt;/span&gt;        &lt;span style="color: rgb(0,0,255)"&gt;Next
&lt;/span&gt;    &lt;span style="color: rgb(0,0,255)"&gt;End&lt;/span&gt; &lt;span style="color: rgb(0,0,255)"&gt;Sub&lt;/span&gt;&lt;/pre&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;p&gt;This code will produce an error stating that "Text" is not a member of object.&amp;nbsp; Users expected type inference to type the variable "cur" as Control.&amp;nbsp; Unfortunately this is "By Design".&amp;nbsp; &lt;/p&gt;
&lt;p&gt;Much of the original .Net Framework was written before the CLR implemented support for generics.&amp;nbsp; As a result all of the collection classes were loosely typed to Object by implementing &lt;a href="http://msdn2.microsoft.com/en-us/library/9eekhta0.aspx"&gt;IEnumerable&lt;/a&gt;.&amp;nbsp; So in this case type inference will correctly type this as Object.&lt;/p&gt;
&lt;p&gt;There are 2 ways to fix this problem. &lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Explicitly type the For Each variable to be the actual type of objects in the collection&lt;/li&gt;
&lt;li&gt;Use a Shim to change the type of the collection. (see &lt;a title="http://blogs.msdn.com/jaredpar/archive/2007/10/04/ienumerable-and-ienumerable-of-t.aspx" href="http://blogs.msdn.com/jaredpar/archive/2007/10/04/ienumerable-and-ienumerable-of-t.aspx"&gt;http://blogs.msdn.com/jaredpar/archive/2007/10/04/ienumerable-and-ienumerable-of-t.aspx&lt;/a&gt;)&lt;/li&gt;&lt;/ol&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=6536165" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/jaredpar/archive/tags/VB/default.aspx">VB</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Orcas/default.aspx">Orcas</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Generics/default.aspx">Generics</category><category domain="http://blogs.msdn.com/jaredpar/archive/tags/Type+Inference/default.aspx">Type Inference</category></item></channel></rss>