<?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>BCL Team Blog</title><link>http://blogs.msdn.com/b/bclteam/</link><description>Base types, Collections, Diagnostics, IO, RegEx...</description><dc:language>en-US</dc:language><generator>Telligent Community 5.6.583.19849 (Build: 5.6.583.19849)</generator><item><title>What’s new in MEF 2 Preview 5? [Alok, Nick]</title><link>http://blogs.msdn.com/b/bclteam/archive/2011/12/19/what-s-new-in-mef-2-preview-5-alok-nick.aspx</link><pubDate>Mon, 19 Dec 2011 19:18:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10249314</guid><dc:creator>BCL Team</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/bclteam/rsscomments.aspx?WeblogPostID=10249314</wfw:commentRss><comments>http://blogs.msdn.com/b/bclteam/archive/2011/12/19/what-s-new-in-mef-2-preview-5-alok-nick.aspx#comments</comments><description>&lt;p&gt;Nearly two months since we published &lt;a href="http://blogs.msdn.com/b/bclteam/archive/2011/10/27/what-s-new-in-mef-version-2-preview-4.aspx"&gt;MEF 2 Preview 4,&lt;/a&gt; we have just&amp;nbsp;posted our &lt;a href="http://mef.codeplex.com/releases/view/79090"&gt;fifth preview&lt;/a&gt; on the MEF CodePlex site.&lt;/p&gt;
&lt;p&gt;The new preview has been shaped by your feedback; everyone who took the time to download, evaluate or comment on the last version, thank you!&lt;/p&gt;
&lt;p&gt;So, what has changed since Preview 4?&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;em&gt;CompositionException.RootCauses&lt;/em&gt;, previously only visible in the debugger, can now be accessed directly in code&lt;/li&gt;
&lt;li&gt;Using &lt;em&gt;RegistrationBuilder&lt;/em&gt;, all interfaces on a part can now be exported using the &lt;em&gt;ExportInterfaces method&lt;/em&gt;&lt;/li&gt;
&lt;li&gt;&lt;em&gt;IDisposable&lt;/em&gt; and &lt;em&gt;IPartImportsSatisfiedNotification&lt;/em&gt; will now be filtered out by &lt;em&gt;RegistrationBuilder&lt;/em&gt; automatically (these should never be exported)&lt;/li&gt;
&lt;li&gt;&lt;em&gt;CompositionProvider&lt;/em&gt; in the ASP.NET MVC integration now exposes &lt;em&gt;ApplicationSharedPartMetadataKey&lt;/em&gt; for those wishing to create their own sharing conventions compatible with the provider&lt;/li&gt;
&lt;li&gt;Some additional performance tuning has been done&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;As we get closer to making our next supported release as part of the .NET Framework, the bar is now high for changes to be included in MEF 2. Even so, we&amp;rsquo;d love to hear about your experiences with the new preview, and planning for MEF 3 is just around the corner. You can get in touch via this blog or through the &lt;a href="http://mef.codeplex.com/discussions"&gt;discussion forum&lt;/a&gt; and &lt;a href="http://mef.codeplex.com/workitem/list/basic"&gt;issue tracker&lt;/a&gt; on CodePlex.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10249314" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/bclteam/archive/tags/MEF/">MEF</category><category domain="http://blogs.msdn.com/b/bclteam/archive/tags/-NET+Framework+4-5+Preview/">.NET Framework 4.5 Preview</category></item><item><title>Sharing with CompositionScopeDefinition in MEF 2 [Alok]</title><link>http://blogs.msdn.com/b/bclteam/archive/2011/12/19/sharing-with-compositionscopedefinition-in-mef2-alok.aspx</link><pubDate>Mon, 19 Dec 2011 17:23:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10249268</guid><dc:creator>BCL Team</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/bclteam/rsscomments.aspx?WeblogPostID=10249268</wfw:commentRss><comments>http://blogs.msdn.com/b/bclteam/archive/2011/12/19/sharing-with-compositionscopedefinition-in-mef2-alok.aspx#comments</comments><description>&lt;p&gt;&lt;em&gt;This post discusses features in the &lt;a href="http://blogs.msdn.com/b/bclteam/archive/2011/10/27/what-s-new-in-mef-version-2-preview-4.aspx"&gt; preview&lt;/a&gt; version of MEF, and some details may change between now and the full release.&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;In the previous &lt;a href="http://blogs.msdn.com/b/bclteam/archive/2011/11/17/exportfactory-amp-lt-t-amp-gt-in-mef-2-alok.aspx"&gt;post&lt;/a&gt;, we introduced &lt;em&gt;ExportFactory&amp;lt;T&amp;gt;&lt;/em&gt; and demonstrated how it can be used to control the lifetimes of MEF parts. In this article we will talk about a new type MEF called &lt;em&gt;CompositionScopeDefinition&lt;/em&gt; that can be used in conjunction with &lt;em&gt;ExportFactory&amp;lt;T&amp;gt;&lt;/em&gt; to control sharing. Let&amp;rsquo;s take a scenario that we could not achieve using what we know currently and how &lt;em&gt;CompositionScopeDefinition&lt;/em&gt; provides the needed control.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;&lt;strong&gt;Important note:&lt;/strong&gt;&lt;/em&gt; &lt;em&gt;CompositionScopeDefinition&lt;/em&gt; is geared towards more advanced, desktop application scenarios. If you're using MEF in an &lt;a href="http://asp.net/mvc"&gt;ASP.NET MVC&lt;/a&gt; web application and want to control sharing and lifetime on a per-HTTP-request level, you should use the &lt;a href="http://blogs.msdn.com/b/bclteam/archive/2011/11/11/using-mef-2-with-asp-net-mvc-3.aspx"&gt;pre-defined ASP.NET MVC integration&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Lets go back to our application block diagram that we built in Part 1 of this article.&lt;/p&gt;
&lt;p&gt;&lt;a href="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-30-50/7484.Figure1.PNG"&gt;&lt;img border="0" alt="" src="http://blogs.msdn.com/resized-image.ashx/__size/550x0/__key/communityserver-blogs-components-weblogfiles/00-00-00-30-50/7484.Figure1.PNG" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Now let&amp;rsquo;s add a few details to this architecture. As our application has grown more complex, we have decided to factor out the data access part into a separate component called &lt;em&gt;DataAccessLayer&lt;/em&gt;, which handles manages the connection to the database and reading and writing to it. In addition to this we also want to add a logger, which also logs some tracking information to the same database. So our slightly expanded functional diagram looks like the following.&lt;/p&gt;
&lt;p&gt;&lt;a href="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-30-50/1373.Figure2.PNG"&gt;&lt;img border="0" alt="" src="http://blogs.msdn.com/resized-image.ashx/__size/550x0/__key/communityserver-blogs-components-weblogfiles/00-00-00-30-50/1373.Figure2.PNG" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;In the context of our scenario, all data access within a single request should be made through the same database connection. In the default configuration, MEF will share a single &lt;em&gt;DatabaseConnection&lt;/em&gt; across the application. How do we instruct MEF to share the database connection per request? Lets start by laying out the class definitions for the different parts.&lt;/p&gt;
&lt;pre&gt;    [Export]
    public class RequestListener
    {
        ExportFactory&amp;lt;RequestHandler&amp;gt; _handlerFactory;

        public RequestListener(ExportFactory&amp;lt;RequestHandler&amp;gt; handlerFactory)
        {
            _handlerFactory = handlerFactory;
        }

        public void HandleRequest()
        {
            using (var request = _handlerFactory.CreateExport())
            {
                request.Value.Process();
            }
        }
    }

    [Export]
    public class RequestHandler
    {
        [ImportingConstructor]
        public RequestHandler(DataAccessLayer dataAccess, Logger logger)
        {
        }

        public void Process()
        {
            //Do stuff using DataAccess and Logger
        }
    }

    [Export]
    public class DataAccessLayer
    {
        [ImportingConstructor]
        public DataAccessLayer(DatabaseConnection conn)
        {
        }
    }

    [Export]
    public class Logger
    {
        [ImportingConstructor]
        public Logger(DatabaseConnection conn)
        {
        }
    }

    [Export]
    public class DatabaseConnection
    {
        public DatabaseConnection()
        {
        }
    }
&lt;/pre&gt;
&lt;h2&gt;Introducing CompositionScopeDefinition&lt;/h2&gt;
&lt;h3&gt;Scenario 5: Sharing within the scope of an ExportFactory&amp;lt;T&amp;gt; instantiation&lt;/h3&gt;
&lt;p&gt;As we can observe as we had in the previous article the &lt;em&gt;RequestListener&lt;/em&gt; class has an &lt;em&gt;ExportFactory&lt;/em&gt; to create instances of the &lt;em&gt;RequestHandler&lt;/em&gt; class. The &lt;em&gt;RequestHandler&lt;/em&gt; now depends on two classes the &lt;em&gt;DataAccess&lt;/em&gt; and the &lt;em&gt;Logger&lt;/em&gt; class, both of which depend on the &lt;em&gt;DatabaseConnection&lt;/em&gt; class. What we want to achieve looks like the following figure.&lt;/p&gt;
&lt;p&gt;&lt;a href="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-30-50/3326.Figure3.PNG"&gt;&lt;img border="0" alt="" src="http://blogs.msdn.com/resized-image.ashx/__size/550x0/__key/communityserver-blogs-components-weblogfiles/00-00-00-30-50/3326.Figure3.PNG" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;If we look from the &lt;em&gt;DatabaseConnection&lt;/em&gt; down to the root of the composition at &lt;em&gt;RequestListener&lt;/em&gt;, we can see that from a composition beginning at the &lt;em&gt;RequestHandler&lt;/em&gt; (the highlighted portion), we can achieve the sharing using standard MEF we have discussed in part 1 of this article. This is one way to figure out how to divide your catalog into scopes, when you hit a sharing pattern that cannot be achieved by using the simple MEF options. We would then need to write the following code to obtain the desired sharing.&lt;/p&gt;
&lt;pre&gt;var listenerLevel = new TypeCatalog(typeof(RequestListener));
var requestLevel = new TypeCatalog(
    typeof(RequestHandler), 
    typeof(Logger), 
    typeof(DataAccessLayer), 
    typeof(DatabaseConnection));

var container = new CompositionContainer(
     new CompositionScopeDefinition(listenerLevel, 
         new [] { new CompositionScopeDefinition(requestLevel, null) }));

var requestListener = container.GetExportedValue&amp;lt;RequestListener&amp;gt;();
requestListener.HandleRequest();
requestListener.HandleRequest();  
&lt;/pre&gt;
&lt;p&gt;The types making up the scenario are distributed between two catalogs &amp;mdash; those that should be created and shared at the request listener level, and those that need to be created and shared at the per-request level. When an &lt;em&gt;ExportFactory&amp;lt;RequestHandler&amp;gt;&lt;/em&gt; is imported into the request listener, the container sees that the &lt;em&gt;RequestHandler&lt;/em&gt; type is within a child scope, so the child scope definition is used to determine the components (including the &lt;em&gt;DatabaseConnection&lt;/em&gt;) that should be shared in the child scope.&lt;/p&gt;
&lt;p&gt;In order for a parent scope to be able to discover a part in a child scope, it has to be imported as an &lt;em&gt;ExportFactory&amp;lt;T&amp;gt;&lt;/em&gt;. If the &lt;em&gt;RequestListener&lt;/em&gt; imported the &lt;em&gt;RequestHandler&lt;/em&gt; type and not an &lt;em&gt;ExportFactory&amp;lt;RequestHandler&amp;gt;&lt;/em&gt;, a &lt;em&gt;CompositionException&lt;/em&gt; would be thrown.&lt;/p&gt;
&lt;p&gt;How have you used &lt;em&gt;CompositionScopeDefintion&lt;/em&gt;? Did you find it easy to use? Are there still sharing scenarios that you cannot achieve? Leave us a message in the comments or in the &lt;a href="http://mef.codeplex.com/discussions"&gt;dicussion forum&lt;/a&gt; on the MEF CodePlex site.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10249268" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/bclteam/archive/tags/MEF/">MEF</category><category domain="http://blogs.msdn.com/b/bclteam/archive/tags/-NET+Framework+4-5+Preview/">.NET Framework 4.5 Preview</category></item><item><title>ExportFactory&lt;T&gt; in MEF 2 [Alok]</title><link>http://blogs.msdn.com/b/bclteam/archive/2011/11/17/exportfactory-amp-lt-t-amp-gt-in-mef-2-alok.aspx</link><pubDate>Fri, 18 Nov 2011 01:12:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10238368</guid><dc:creator>BCL Team</dc:creator><slash:comments>4</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/bclteam/rsscomments.aspx?WeblogPostID=10238368</wfw:commentRss><comments>http://blogs.msdn.com/b/bclteam/archive/2011/11/17/exportfactory-amp-lt-t-amp-gt-in-mef-2-alok.aspx#comments</comments><description>&lt;p&gt;&lt;em&gt;&lt;strong&gt;This post discusses features in the &lt;a href="http://blogs.msdn.com/b/bclteam/archive/2011/10/27/what-s-new-in-mef-version-2-preview-4.aspx"&gt;preview version of MEF&lt;/a&gt;, and some details may change between now and the full release.&lt;/strong&gt;&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;In the first version of MEF there are only two notions of lifetime: A shared global lifetime or a per instance lifetime. In MEF 2 Preview 4 new support has been added to enable a finer grained control over the lifetime and sharing of parts. Before we can cover those changes in detail, we need to introduce &lt;em&gt;ExportFactory&amp;lt;T&amp;gt;&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;Let us consider a simple application scenario of a &lt;em&gt;RequestListener&lt;/em&gt;, which spawns a &lt;em&gt;RequestHandler&lt;/em&gt;, which uses a &lt;em&gt;DatabaseConnection&lt;/em&gt; to connect to a data source (Fig 1):&lt;/p&gt;
&lt;p&gt;&lt;a href="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-30-50/2022.Figure1.PNG"&gt;&lt;img alt="" src="http://blogs.msdn.com/resized-image.ashx/__size/550x0/__key/communityserver-blogs-components-weblogfiles/00-00-00-30-50/2022.Figure1.PNG" border="0" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Let us also consider the following parts that implement the &lt;em&gt;RequestHandler&lt;/em&gt; and &lt;em&gt;DatabaseConnection&lt;/em&gt;.&lt;/p&gt;
&lt;pre&gt;    [Export]
    public class RequestHandler
    {
        [ImportingConstructor]
        public RequestHandler(DatabaseConnection connection)
        {
        }
    }

    [Export]
    public class DatabaseConnection
    {
        public DatabaseConnection()
        {
        }
    }
&lt;/pre&gt;
&lt;h2&gt;In MEF version 1...&lt;/h2&gt;
&lt;p&gt;To better illustrate the new capabilities we&amp;rsquo;ve added in MEF 2, some of the scenarios that could be achieved in MEF version 1 are discussed below.&lt;/p&gt;
&lt;h3&gt;Scenario 1: RequestHandler and DatabaseConnection instances are shared&lt;/h3&gt;
&lt;p&gt;When we first start building our app, we are being very conservative about resources and not knowing our load we spin up a single instance of &lt;em&gt;RequestHandler&lt;/em&gt; and &lt;em&gt;DatabaseConnection&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;We could instantiate an instance of the RequestHandler using the following code.&lt;/p&gt;
&lt;pre&gt;TypeCatalog global = new TypeCatalog(
    typeof(RequestHandler), typeof(DatabaseConnection));
var container = new CompositionContainer(global);
var requestHandler = container.GetExportedValue&amp;lt;RequestHandler&amp;gt;();
&lt;/pre&gt;
&lt;p&gt;Regardless of the number of times &lt;em&gt;GetExportedValue()&lt;/em&gt; is called, the same instance of the &lt;em&gt;RequestHandler&lt;/em&gt; is always returned (Fig 2).&lt;/p&gt;
&lt;p&gt;&lt;a href="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-30-50/4834.Figure2.PNG"&gt;&lt;img alt="" src="http://blogs.msdn.com/resized-image.ashx/__size/550x0/__key/communityserver-blogs-components-weblogfiles/00-00-00-30-50/4834.Figure2.PNG" border="0" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h3&gt;Scenario 2: Separate instances of RequestHandler and DatabaseConnection&lt;/h3&gt;
&lt;p&gt;Now we realize that the throughput for our system is really poor, since we can only process one request at a time. So in order to increase our throughput, we spin up new instance of &lt;em&gt;RequestHandler&lt;/em&gt; and &lt;em&gt;DatabaseConnection&lt;/em&gt; for every request that comes in. In order to achieve this with MEF we can put a &lt;em&gt;PartCreationPolicyAttribute&lt;/em&gt; on &lt;em&gt;RequestHandler&lt;/em&gt; and &lt;em&gt;DatabaseConnection&lt;/em&gt;:&lt;/p&gt;
&lt;pre&gt;    [PartCreationPolicy(CreationPolicy.NonShared)]
    public class RequestHandler { &amp;hellip; }

    [PartCreationPolicy(CreationPolicy.NonShared)]
    public class DatabaseConnection { &amp;hellip; }
&lt;/pre&gt;
&lt;p&gt;&lt;a href="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-30-50/8255.Figure3.PNG"&gt;&lt;img alt="" src="http://blogs.msdn.com/resized-image.ashx/__size/550x0/__key/communityserver-blogs-components-weblogfiles/00-00-00-30-50/8255.Figure3.PNG" border="0" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Now, with the same invoking code to &lt;em&gt;GetExportedValue()&lt;/em&gt;, we now get new instances for &lt;em&gt;RequestHandler&lt;/em&gt; and &lt;em&gt;DatabaseConnection&lt;/em&gt; every time.&lt;/p&gt;
&lt;h3&gt;Scenario 3: RequestHandler instances created and DatabaseConnection instance is shared&lt;/h3&gt;
&lt;p&gt;Our throughput is now up, but creating a new database connection per request is really taking a toll on our database server which can handle only a few open connections at a time. To ease the load on our database server we hence decide, that we will share a single instance of a &lt;em&gt;DatabaseConnection&lt;/em&gt;, among multiple &lt;em&gt;RequestHandler&lt;/em&gt;s. This will give us our throughput improvements without overloading our database server. We can achieve the following by getting rid of the &lt;em&gt;PartCreationPolicy&lt;/em&gt; we have on the &lt;em&gt;DatabaseConnection&lt;/em&gt; class, so it would now look like the following:&lt;/p&gt;
&lt;pre&gt;    public class DatabaseConnection { &amp;hellip; }
&lt;/pre&gt;
&lt;p&gt;With the removal of this attribute, we now get only a new instance of the &lt;em&gt;RequestHandler&lt;/em&gt; every time &lt;em&gt;GetExportedValue()&lt;/em&gt; is called, which all share a single instance of the &lt;em&gt;DatabaseConnection&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;&lt;a href="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-30-50/0880.Figure4.PNG"&gt;&lt;img alt="" src="http://blogs.msdn.com/resized-image.ashx/__size/550x0/__key/communityserver-blogs-components-weblogfiles/00-00-00-30-50/0880.Figure4.PNG" border="0" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;In MEF 2... introducing ExportFactory&amp;lt;T&amp;gt;&lt;/h2&gt;
&lt;p&gt;The above scenarios that we have seen are the sharing scenarios that could be achieved using MEF in the past releases. However there is one glaring omission in the matrix that we presented above. What if I wanted a multiple instance of a dependency from a single instance of what it was depending on? To put it in the context of our example, how does the &lt;em&gt;RequestListener&lt;/em&gt; class which was the first block in our diagram create multiple instances of the &lt;em&gt;RequestHandler&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;This brings us to:&lt;/p&gt;
&lt;h3&gt;Scenario 4: Single instance of RequestListener and multiple (dynamic) instances of RequestHandler&lt;/h3&gt;
&lt;p&gt;In order to enable this scenario, in the latest version of MEF, we introduce a new class called the &lt;em&gt;ExportFactory&amp;lt;T&amp;gt;&lt;/em&gt;. &lt;em&gt;ExportFactory&amp;lt;T&amp;gt;&lt;/em&gt; may be familiar to Silverlight 4 developers, since it was shipped as a part of the Silverlight 4 SDK. The export factory allows us to create new instances of dependencies and control the lifetime of the created parts.&lt;/p&gt;
&lt;p&gt;Let us go back to our initial block diagram and write out the code for the &lt;em&gt;RequestListener&lt;/em&gt; class.&lt;/p&gt;
&lt;pre&gt;    [Export]
    public class RequestListener
    {
        ExportFactory&amp;lt;RequestHandler&amp;gt; _factory;

        [ImportingConstructor]
        public RequestListener(ExportFactory&amp;lt;RequestHandler&amp;gt; factory)
        {
            _factory = factory;
        }

        public void HandleRequest()
        {
            using (var instance = _factory.CreateExport())
            {
                instance.Value.Process();
            }
        }
    }
&lt;/pre&gt;
&lt;p&gt;Now we see in the code that instead of importing a &lt;em&gt;RequestHandler&lt;/em&gt; as a depedency, we import an &lt;em&gt;ExportFactory&amp;lt;RequestHandler&amp;gt;&lt;/em&gt;. MEF treats &lt;em&gt;ExportFactory&amp;lt;T&amp;gt;&lt;/em&gt; as a special class, and will automatically hook it up to the part providing &lt;em&gt;T&lt;/em&gt;. We then added a &lt;em&gt;HandleRequest()&lt;/em&gt; member, which does the work of instantiating the &lt;em&gt;RequestHandler&lt;/em&gt;. The &lt;em&gt;CreateExport()&lt;/em&gt; method creates an &lt;em&gt;ExportLifetimeContext&amp;lt;T&amp;gt;&lt;/em&gt;, which implements &lt;em&gt;IDisposable&lt;/em&gt;, which is used to control the lifetime of the objects created by the factory. Since the listener is creating the parts, we can get also get rid of the &lt;em&gt;PartCreationPolicy&lt;/em&gt; attribute on the &lt;em&gt;RequestHandler&lt;/em&gt;. Putting all the pieces together a call to:&lt;/p&gt;
&lt;pre&gt;TypeCatalog global = new TypeCatalog(typeof(RequestHandler), typeof(DatabaseConnection) , typeof(RequestListener));
var container = new CompositionContainer(global);
var requestListener = container.GetExportedValue&amp;lt;RequestListener&amp;gt;();
requestListener.HandleRequest();
&lt;/pre&gt;
&lt;p&gt;will result in the following composition graph:&lt;/p&gt;
&lt;p&gt;&lt;a href="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-30-50/3566.Figure5.PNG"&gt;&lt;img alt="" src="http://blogs.msdn.com/resized-image.ashx/__size/550x0/__key/communityserver-blogs-components-weblogfiles/00-00-00-30-50/3566.Figure5.PNG" border="0" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Stay tuned for part two of this post where we talk about some more sharing scenarios and how we can use the new scoping enhancements in MEF in conjunction with &lt;em&gt;ExportFactory&amp;lt;T&amp;gt;&lt;/em&gt; to accomplish these.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10238368" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/bclteam/archive/tags/MEF/">MEF</category><category domain="http://blogs.msdn.com/b/bclteam/archive/tags/-NET+Framework+4-5+Preview/">.NET Framework 4.5 Preview</category></item><item><title>Using MEF 2 with ASP.NET MVC 3 [Nick]</title><link>http://blogs.msdn.com/b/bclteam/archive/2011/11/11/using-mef-2-with-asp-net-mvc-3.aspx</link><pubDate>Fri, 11 Nov 2011 23:47:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10236371</guid><dc:creator>BCL Team</dc:creator><slash:comments>4</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/bclteam/rsscomments.aspx?WeblogPostID=10236371</wfw:commentRss><comments>http://blogs.msdn.com/b/bclteam/archive/2011/11/11/using-mef-2-with-asp-net-mvc-3.aspx#comments</comments><description>&lt;p&gt;&lt;strong&gt;&lt;em&gt;This post discusses features in the &lt;a href="http://blogs.msdn.com/b/bclteam/archive/2011/10/27/what-s-new-in-mef-version-2-preview-4.aspx"&gt;preview version of MEF&lt;/a&gt;, and some details may change between now and the full release. &lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The latest MEF preview includes a new assembly, &lt;em&gt;System.ComponentModel.Composition.Web.Mvc.CodePlex.dll&lt;/em&gt;, that simplifies the task of building flexible, testable and maitainable &lt;a href="http://asp.net/mvc"&gt;ASP.NET MVC&lt;/a&gt; web applications.&lt;/p&gt;
&lt;p&gt;To achieve this it:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;provides dependency injection for &lt;em&gt;Controller&lt;/em&gt; classes,&lt;/li&gt;
&lt;li&gt;defines a simple convention for identifying and configuring MEF parts,&lt;/li&gt;
&lt;li&gt;maps the lifetime of part instances to the ASP.NET request processing lifecycle, and&lt;/li&gt;
&lt;li&gt;simplifies the use of dependency injection in action filter attributes and model binders.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The .NET 4.0 version of the 'composition provider' assembly that can be &lt;a href="http://mef.codeplex.com/releases/view/75766"&gt;downloaded from CodePlex&lt;/a&gt; only supports the preview version of MEF 2 with which it is bundled, and requires ASP.NET MVC 3. We expect to release the final version as a &lt;a href="http://nuget.org"&gt;NuGet&lt;/a&gt; package targeting the MEF 2 RTM.&lt;/p&gt;
&lt;p&gt;In this article, we'll walk through the process of setting up basic composition for controllers and parts. We'll then examine some of the deeper support provided for other ASP.NET MVC features. You'll need some familiarity with both managed composition (MEF/IoC) and ASP.NET MVC.&lt;/p&gt;
&lt;p&gt;This post is accompanied by a sample application called 'Fabrikam Books.' You may wish to &lt;a href="http://mef.codeplex.com/releases/view/76703"&gt;download the sample solution now&lt;/a&gt; so that you can explore and experiment with runnable code.&lt;/p&gt;
&lt;h2&gt;Enabling the composition provider in an ASP.NET MVC application&lt;/h2&gt;
&lt;p&gt;Setting up the composition provider is &lt;strong&gt;super&lt;/strong&gt; simple:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;If you haven't already, create your ASP.NET MVC 3 web application.&lt;/li&gt;
&lt;li&gt;Add assembly references to:
&lt;ul&gt;
&lt;li&gt;&lt;em&gt;System.ComponentModel.Composition.CodePlex.dll&lt;/em&gt;&lt;/li&gt;
&lt;li&gt;&lt;em&gt;System.ComponentModel.Composition.Web.Mvc.CodePlex.dll&lt;/em&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;Use Visual Studio to create a folder in the root of your web application project called &lt;em&gt;Parts&lt;/em&gt;&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;The last step &amp;mdash; creating a &lt;em&gt;Parts&lt;/em&gt; folder &amp;mdash; is a good way to get started. In the long run, you may reorganise and have several parts folders in your project, but the important thing is that parts for composition live in a namespace that includes a 'Parts' element.&lt;/p&gt;
&lt;p&gt;The composition provider from this point on is &lt;strong&gt;configuration-free&lt;/strong&gt;. You can press F5 and watch your site run &amp;mdash; so far nothing obvious should have changed, but under the covers, ASP.NET will be using MEF to construct the controllers used to handle requests! Before you can take advantage of this, you'll need to create some parts.&lt;/p&gt;
&lt;h2&gt;Creating a part&lt;/h2&gt;
&lt;p&gt;ASP.NET MVC already defines some important roles for application classes &amp;ndash; there are controllers, models, views, filters and so-on. There are many other roles that make up a complete application; classes for:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Accessing data&lt;/li&gt;
&lt;li&gt;Performing calculations&lt;/li&gt;
&lt;li&gt;Communicating with other sites and web services&lt;/li&gt;
&lt;li&gt;The secret sauce that makes your application special!&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;When using the composition provider for ASP.NET MVC, these classes can be implemented as parts.&lt;/p&gt;
&lt;h3&gt;The Parts folder&lt;/h3&gt;
&lt;p&gt;By convention, classes created in the &lt;em&gt;Parts&lt;/em&gt; namespace are assumed to be parts for managed composition. Create a regular class by right-clicking on the &lt;em&gt;Parts&lt;/em&gt; folder and selecting &amp;ldquo;Add New&amp;rdquo; &amp;rarr; &amp;ldquo;Class&amp;rdquo;. Call the class &amp;ldquo;TraceLogger&amp;rdquo;.&lt;/p&gt;
&lt;pre&gt;    public class TraceLogger
    {
        public void Write(string text)
        {
            System.Diagnostics.Trace.WriteLine(text);
        }
    }
&lt;/pre&gt;
&lt;h3&gt;Exporting contracts&lt;/h3&gt;
&lt;p&gt;The goal of managed composition is to decouple the parts in an application, usually through the use of interfaces as &amp;lsquo;contracts&amp;rsquo; that a part provides to other parts.&lt;/p&gt;
&lt;p&gt;In the &lt;em&gt;Parts&lt;/em&gt; folder, create a new interface called &amp;ldquo;ILogger&amp;rdquo; and declare a &amp;ldquo;Write&amp;rdquo; method on it:&lt;/p&gt;
&lt;pre&gt;    public interface ILogger
    {
        void Write(string text);
    }
&lt;/pre&gt;
&lt;p&gt;Now go back to the &lt;em&gt;TraceLogger&lt;/em&gt; part and implement the &lt;em&gt;ILogger&lt;/em&gt; interface:&lt;/p&gt;
&lt;pre&gt;    public class TraceLogger : ILogger { &amp;hellip; }
&lt;/pre&gt;
&lt;p&gt;By convention, the composition provider assumes that any interfaces implemented by a part are the exports that it provides to other parts in the system.&lt;/p&gt;
&lt;p&gt;In the included sample application, you can find a number of parts under its &lt;em&gt;Parts&lt;/em&gt; folder. The simplest example is &lt;em&gt;TraceLogger&lt;/em&gt;, under &lt;em&gt;Parts/Tracing&lt;/em&gt;. The &lt;em&gt;FabrikamBooksDbContext&lt;/em&gt; part, under &lt;em&gt;Parts/Data&lt;/em&gt;, exports the &lt;em&gt;IDbContext&lt;/em&gt; contract. The constructor of this part imports an &lt;em&gt;ILogger&lt;/em&gt;, showing how parts can consume the contracts provided by other parts.&lt;/p&gt;
&lt;h2&gt;Using a part from a controller&lt;/h2&gt;
&lt;p&gt;If your ASP.NET MVC application was created from the default template, you will have a controller class called &amp;ldquo;HomeController&amp;rdquo; in the application&amp;rsquo;s &lt;em&gt;Controllers&lt;/em&gt; folder.&lt;/p&gt;
&lt;p&gt;Controllers are the primary place to consume parts &amp;ndash; by adding a constructor to &lt;em&gt;HomeController&lt;/em&gt; that accepts an &lt;em&gt;ILogger&lt;/em&gt;, the &lt;em&gt;HomeController&lt;/em&gt; can import the &lt;em&gt;ILogger&lt;/em&gt; contract supplied by the &lt;em&gt;TraceLogger&lt;/em&gt; part:&lt;/p&gt;
&lt;pre&gt;    public class HomeController : Controller
    {
        ILogger _logger;

        public HomeController(ILogger logger)
        {
            _logger = logger;
        }
        
        public ActionResult Index()
        {
            _logger.Write("Executing the Index() action method.");
            return View();
        }
    }
&lt;/pre&gt;
&lt;p&gt;Whenever the &lt;em&gt;HomeController.Index()&lt;/em&gt; action is executed, the message from the &lt;em&gt;_logger.Write()&lt;/em&gt; call will be written to the application&amp;rsquo;s debug output window (try it!).&lt;/p&gt;
&lt;p&gt;In the same way that &lt;em&gt;HomeController&lt;/em&gt; can import the &lt;em&gt;ILogger&lt;/em&gt; contract by declaring a constructor parameter, other parts can import instances of each other. This is how, from small pieces, the managed composition system can build up complex applications to do interesting things.&lt;/p&gt;
&lt;p&gt;In the sample application, &lt;em&gt;HomeController&lt;/em&gt; can be found under the &lt;em&gt;Controllers&lt;/em&gt; folder.&lt;/p&gt;
&lt;h3&gt;Property imports&lt;/h3&gt;
&lt;p&gt;Although the composition provider will automatically supply constructor parameters to controllers and other parts, it will not automatically set properties, even when those properties are of a type supplied by another part. To mark a property as being an import, apply the MEF &lt;em&gt;Import&lt;/em&gt; attribute to the property declaration.&lt;/p&gt;
&lt;h2&gt;The composition scopes&lt;/h2&gt;
&lt;p&gt;Scope or 'lifetime' determines how long a part created by the composition provider will live, and how it will be shared between other parts.&lt;/p&gt;
&lt;h3&gt;Request scope&lt;/h3&gt;
&lt;p&gt;When instances of parts are created during the processing of a web request, those parts will be shared within the scope of that web request.&lt;/p&gt;
&lt;p&gt;So, if &lt;em&gt;CatalogController&lt;/em&gt; requires both a &lt;em&gt;ProductRepository&lt;/em&gt; part and a &lt;em&gt;CategoryRepository&lt;/em&gt; part, and each repository requires a &lt;em&gt;DataContext&lt;/em&gt;, then &lt;span style="text-decoration: underline;"&gt;the same &lt;em&gt;DataContext&lt;/em&gt; part instance&lt;/span&gt; will be shared by both repositories &lt;span style="text-decoration: underline;"&gt;within a single web request&lt;/span&gt;. Within different web requests, different part instances will be created and shared.&lt;/p&gt;
&lt;p&gt;Once processing of a request completes, the parts that were created during the web request are no longer required. If the parts implement &lt;em&gt;IDisposable&lt;/em&gt;, their &lt;em&gt;Dispose()&lt;/em&gt; methods will be called automatically. This is a great way to make sure that resources like database connections, files and service proxies are always released correctly.&lt;/p&gt;
&lt;p&gt;In the Fabrikam Books sample, &lt;em&gt;FabrikamDbContext&lt;/em&gt; is an example of a request-scoped part. It can be found under &lt;em&gt;Parts/Data&lt;/em&gt;.&lt;/p&gt;
&lt;h3&gt;The application scope&lt;/h3&gt;
&lt;p&gt;Occasionally, creating a part instance per-request is not the desired behavior. For example, a part implementing an in-memory cache of category names might be created once and then shared by all parts in all requests served by a web application.&lt;/p&gt;
&lt;p&gt;To mark a part as being shared at the application level, apply the ApplicationShared attribute:&lt;/p&gt;
&lt;pre&gt;    [ApplicationShared]
    public class CategoryCache : ICache&amp;lt;Category&amp;gt; { &amp;hellip; }
&lt;/pre&gt;
&lt;p&gt;Application-shared parts can only depend on contracts supplied by other application-shared parts.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Be careful&lt;/strong&gt; when creating such parts, they will need to be thread-safe.&lt;/p&gt;
&lt;p&gt;In the sample, &lt;em&gt;TraceLogger&lt;/em&gt; is implemented as an application-shared part. It can be found under &lt;em&gt;Parts/Tracing&lt;/em&gt;.&lt;/p&gt;
&lt;h3&gt;Non-shared parts, contract names and wiring&lt;/h3&gt;
&lt;p&gt;MEF comes with many additional options for wiring parts together. By applying attributes to part types, the &lt;a href="http://blogs.msdn.com/b/bclteam/archive/2011/11/03/overriding-part-registration-conventions-with-the-mef-attributes-nick.aspx"&gt;defaults for sharing and contract matching can be overridden&lt;/a&gt;.&lt;/p&gt;
&lt;h2&gt;Adding parts from additional assemblies&lt;/h2&gt;
&lt;p&gt;Sometimes, perhaps because code needs to be shared between multiple applications, a web application will need to be implemented with more than one assembly.&lt;/p&gt;
&lt;p&gt;To find parts in assemblies other than the main web application, first, the parts must be in a namespace that includes a segment &amp;lsquo;Parts&amp;rsquo; such as &amp;ldquo;MyApp.OtherAssembly.Parts&amp;rdquo; or even &amp;ldquo;MyApp.Parts.OtherAssembly&amp;rdquo;.&lt;/p&gt;
&lt;p&gt;Then, to ensure it is found by the composition provider, the assembly must be explicitly added during application startup in Global.asax.&lt;/p&gt;
&lt;pre&gt;    protected void Application_Start()
    {
        Assembly otherAssembly = ...;
        CompositionProvider.AddPartsAssembly(otherAssembly);
    }
&lt;/pre&gt;
&lt;p&gt;Having to use a &lt;em&gt;Parts&lt;/em&gt; namespace for all parts may seem a little excessive, but it is a good reminder that not every class should be a part. Parts are the &amp;lsquo;coarse-grained&amp;rsquo; chunks that make up an application. Assemblies that add non-trivial functionality will almost always have a large number of additional supporting classes that the parts in the assembly use, but that are not parts themselves.&lt;/p&gt;
&lt;h2&gt;Action filter attributes&lt;/h2&gt;
&lt;p&gt;Action filter attributes can be applied to ASP.NET MVC controllers or action methods in order to change the way the action is executed. Action filter attributes are not created by the composition provider, but can be provided with contracts via properties marked with the &lt;em&gt;Import&lt;/em&gt; attribute.&lt;/p&gt;
&lt;pre&gt;    public class SaveChangesAttribute : ActionFilterAttribute
    {
        [Import]
        public IDbContext DbContext { get; set; }

        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            if (filterContext.Exception == null)
                DbContext.SaveChanges();
        }
    }
&lt;/pre&gt;
&lt;p&gt;The sample includes &lt;em&gt;Parts/Data/SaveChangesAttribute.cs&lt;/em&gt;. This is applied to methods on &lt;em&gt;Controllers/HomeController.cs&lt;/em&gt;.&lt;/p&gt;
&lt;h2&gt;Model binders&lt;/h2&gt;
&lt;p&gt;The final place in ASP.NET MVC where the composition provider can be used is to create model binders. These parts transform HTTP request information into strongly-typed objects that can be used in action methods and elsewhere.&lt;/p&gt;
&lt;p&gt;Model binders are regular parts and appear under the &lt;em&gt;Parts&lt;/em&gt; folder, but must also be marked with the &lt;em&gt;ModelBinderExport&lt;/em&gt; attribute so that the binder is associated with the type of model that it can bind.&lt;/p&gt;
&lt;pre&gt;    [ModelBinderExport(typeof(Book))]
    public class BookModelBinder : IModelBinder { &amp;hellip; }
&lt;/pre&gt;
&lt;p&gt;A full model binder example is given in the Fabrikam Books sample, under &lt;em&gt;Parts/Binding/BookModelBinder.cs&lt;/em&gt;.&lt;/p&gt;
&lt;h2&gt;Summary&lt;/h2&gt;
&lt;p&gt;The composition provider for ASP.NET MVC is a great step towards making your ASP.NET MVC applications more flexible, testable and maintainable.&lt;/p&gt;
&lt;p&gt;Using managed composition to construct parts at runtime is only a small part of the picture. The real value in this technique is that it promotes good design by separating the design of contracts from the parts that implement them.&lt;/p&gt;
&lt;p&gt;Some good sources for discussion of these concepts are:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="http://www.manning.com/seemann/"&gt;Mark Seemann's book&lt;/a&gt; on dependency injection in .NET&lt;/li&gt;
&lt;li&gt;&lt;a href="http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod"&gt;The SOLID principles&lt;/a&gt; described by Bob Martin&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;It is our hope that the combination of MEF and ASP.NET MVC 3 makes for an enjoyable and rewarding development experience. We'd love to hear your feedback and suggestions!&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;&lt;em&gt;&lt;a href="http://mef.codeplex.com/releases/view/75766"&gt;Download MEF 2 Preview 4&lt;/a&gt; from the CodePlex site.&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10236371" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/bclteam/archive/tags/MEF/">MEF</category><category domain="http://blogs.msdn.com/b/bclteam/archive/tags/-NET+Framework+4-5+Preview/">.NET Framework 4.5 Preview</category></item><item><title>Overriding part registration conventions with the MEF attributes [Nick]</title><link>http://blogs.msdn.com/b/bclteam/archive/2011/11/03/overriding-part-registration-conventions-with-the-mef-attributes-nick.aspx</link><pubDate>Thu, 03 Nov 2011 23:49:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10233807</guid><dc:creator>BCL Team</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/bclteam/rsscomments.aspx?WeblogPostID=10233807</wfw:commentRss><comments>http://blogs.msdn.com/b/bclteam/archive/2011/11/03/overriding-part-registration-conventions-with-the-mef-attributes-nick.aspx#comments</comments><description>&lt;p&gt;&lt;strong&gt;&lt;em&gt;This post discusses features in the &lt;a href="http://blogs.msdn.com/b/bclteam/archive/2011/10/27/what-s-new-in-mef-version-2-preview-4.aspx"&gt;preview version of MEF&lt;/a&gt;, and some details may change between now and the full release. &lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;One of the big advances made in the &lt;a href="http://blogs.msdn.com/b/bclteam/archive/2011/10/27/what-s-new-in-mef-version-2-preview-4.aspx"&gt;new MEF preview&lt;/a&gt; is a &lt;a href="http://blogs.msdn.com/b/bclteam/archive/2011/11/01/getting-started-with-convention-based-part-registration-in-mef-version-2.aspx"&gt;convention-driven programming model&lt;/a&gt; aimed at eliminating repetitive attribute usage.&lt;/p&gt;
&lt;p&gt;In this new model, the MEF attributes like &lt;em&gt;Export&lt;/em&gt; and &lt;em&gt;Import&lt;/em&gt; have a new role as the clean and powerful mechanism for overriding the registration conventions.&lt;/p&gt;
&lt;h2&gt;Configuration by exception&lt;/h2&gt;
&lt;p&gt;The power in convention-driven rules is that they require 'constant effort' to handle an arbitrary number of parts.&lt;/p&gt;
&lt;pre&gt;    var registrationBuilder = new RegistrationBuilder();

    registrationBuilder.ForTypesDerivedFrom&amp;lt;IMessageHandler&amp;gt;()
        .Export&amp;lt;IMessageHandler&amp;gt;()
        .SetCreationPolicy(CreationPolicy.NonShared);
&lt;/pre&gt;
&lt;p&gt;The rule above remains unchanged whether there are 10 or 10,000 message handlers in an application, while using explicit configuration for each hander would result in extra effort expended for every handler added.&lt;/p&gt;
&lt;p&gt;Inevitably, there are edge cases and parts for which a rule doesn&amp;rsquo;t quite fit. How these cases are handled has an impact on the effectiveness and maintainability of a convention-based system.&lt;/p&gt;
&lt;h3&gt;Handling non-conforming parts (&amp;ldquo;exceptions&amp;rdquo;) via rules&lt;/h3&gt;
&lt;p&gt;It is possible to embed exceptions to part discovery/configuration rules into the rules themselves. This approach does not scale well to many parts or parts distributed between loosely-coupled assemblies.&lt;/p&gt;
&lt;p&gt;In an application with 50 message handler parts, where 10% have some need of special handling, conventions in MEF's syntax would look like:&lt;/p&gt;
&lt;pre&gt;    registrationBuilder.ForTypesMatching(t =&amp;gt;
           t != typeof(OrderPlacedMessageHandler) &amp;amp;&amp;amp;
           t != typeof(NewCustomerMessageHandler) &amp;amp;&amp;amp;
           t != typeof(CheckoutMessageHandler) &amp;amp;&amp;amp;
           t != typeof(CheckBouncedMessageHandler) &amp;amp;&amp;amp;
           t != typeof(OutOfStockMessageHandler) &amp;amp;&amp;amp;
           typeof(IMessageHandler).IsAssignableFrom(t))
        .Export&amp;lt;IMessageHandler&amp;gt;()
        .SetCreationPolicy(CreationPolicy.NonShared);

    // Special contract name
    registrationBuilder.ForType&amp;lt;OrderPlacedMessageHandler&amp;gt;()
        .Export&amp;lt;IMessageHandler&amp;gt;(x =&amp;gt; x.Named("orders"))
        .SetCreationPolicy(CreationPolicy.NonShared);

    // Default creation policy
    registrationBuilder.ForType&amp;lt;NewCustomerMessageHandler&amp;gt;()
        .Export&amp;lt;IMessageHandler&amp;gt;();

    // Similar single-component rules for remaining three parts above.
    // ...
&lt;/pre&gt;
&lt;p&gt;This has the following issues:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Applying an exception requires tinkering with the host, which is more complicated than changing an individual part&lt;/li&gt;
&lt;li&gt;As soon as there is even one exception, the declarative 'syntactic sugar' of &lt;em&gt;ForTypesDerivedFrom()&lt;/em&gt; becomes inapplicable&lt;/li&gt;
&lt;li&gt;All exceptional types must be visible from the code defining the rule - this does not work well with dynamic discovery e.g. &lt;em&gt;DirectoryCatalog&lt;/em&gt;&lt;/li&gt;
&lt;li&gt;The rule becomes unreadable and verbose&lt;/li&gt;
&lt;li&gt;Keeping the 'shared' aspects of the conventions in sync between the single-component registrations and the general case may introduce errors&lt;/li&gt;
&lt;li&gt;The rule text may be a point of source control contention on large product teams&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;Handling exceptions via attributes&lt;/h3&gt;
&lt;p&gt;Fortunately, MEF has deep support for attributed configuration, which provides a way to specify exceptions to the rules without the issues discussed above.&lt;/p&gt;
&lt;p&gt;In a MEF application, the rule can remain unchanged.&lt;/p&gt;
&lt;pre&gt;    registrationBuilder.ForTypesDerivedFrom&amp;lt;IMessageHandler&amp;gt;()
        .Export&amp;lt;IMessageHandler&amp;gt;()
        .SetCreationPolicy(CreationPolicy.NonShared);
&lt;/pre&gt;
&lt;p&gt;Then, for example &lt;em&gt;OrderPlacedMessageHandler&lt;/em&gt; can have its particular contract name expressed by the addition of an export attribute.&lt;/p&gt;
&lt;pre&gt;    [Export("orders", typeof(IMessageHandler))]
    class OrderPlacedMessageHandler : IMessageHandler {
    }
&lt;/pre&gt;
&lt;p&gt;The &lt;em&gt;NewCustomerMessageHandler&lt;/em&gt; can modify its creation policy.&lt;/p&gt;
&lt;pre&gt;    [PartCreationPolicy(CreationPolicy.NonShared)]
    class NewCustomerMessageHandler : IMessageHandler {
    }
&lt;/pre&gt;
&lt;p&gt;In contrast with the rule-based approach preceding it, the attributed approach has the following benefits:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;A developer applying an exception only needs to deal with the aspect of the part they want to configure, rather than unrelated hosting code&lt;/li&gt;
&lt;li&gt;The rule does not change in the presence of exceptions&lt;/li&gt;
&lt;li&gt;There is no duplication of the parts of the rule that are not affected by the exception&lt;/li&gt;
&lt;li&gt;The rule is not coupled to the implementation types&lt;/li&gt;
&lt;li&gt;Developers viewing the 'exceptional' part source code can see that it is treated differently, for example, avoiding threading bugs caused by variations in the sharing model&lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;How attributes and rules interact&lt;/h2&gt;
&lt;p&gt;Where a rule and an applied attribute overlap, the attribute will always take precendence over the rule.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;&lt;em&gt; MEF attributes in a part&amp;rsquo;s source file always override any rules that affect the same aspect of the same member. &lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The groups of attributes that are considered &amp;lsquo;aspects&amp;rsquo; of a member are:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Export - the &lt;em&gt;Export&lt;/em&gt; attribute, &lt;em&gt;ExportMetadata&lt;/em&gt;, &lt;em&gt;InheritedExport&lt;/em&gt;, custom export and metadata attributes&lt;/li&gt;
&lt;li&gt;Import - the &lt;em&gt;Import&lt;/em&gt; and &lt;em&gt;ImportMany&lt;/em&gt; attributes&lt;/li&gt;
&lt;li&gt;Constructor selection - the &lt;em&gt;ImportingConstructor&lt;/em&gt; attribute&lt;/li&gt;
&lt;li&gt;Part creation policy - the &lt;em&gt;PartCreationPolicy&lt;/em&gt; attribute&lt;/li&gt;
&lt;li&gt;Part metadata - the &lt;em&gt;PartMetadata&lt;/em&gt; attribute&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The source code items considered as a single member for the purpose of convention overrides are:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The class declaration&lt;/li&gt;
&lt;li&gt;All constructors, considered as one group&lt;/li&gt;
&lt;li&gt;A single constructor parameter within a constructor&lt;/li&gt;
&lt;li&gt;A single property&lt;/li&gt;
&lt;li&gt;A single method&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Examples&lt;/h2&gt;
&lt;p&gt;Let&amp;rsquo;s take a look at some common situations where attributes may be used to override conventions.&lt;/p&gt;
&lt;h3&gt;Implementing decorators by changing the exported contract name&lt;/h3&gt;
&lt;p&gt;In the Decorator Design Pattern, one part 'wraps' another part, providing the same contract but adding funtionality to what the wrapped part provides.&lt;/p&gt;
&lt;p&gt;For this scenario, an example convention specifies that public interfaces on a certain set of types are exported:&lt;/p&gt;
&lt;pre&gt;    registrationBuilder.ForTypesMatching(t =&amp;gt; t.Namespace.EndsWith(".Parts"))
        .ExportInterfaces(i =&amp;gt; i.IsPublic);
&lt;/pre&gt;
&lt;p&gt;The &lt;em&gt;RemoteProductRepository&lt;/em&gt; part provides the &lt;em&gt;IProductRepository&lt;/em&gt; contract, while a second part, &lt;em&gt;ProductCache&lt;/em&gt;, is introduced in order to improve product retrieval performance.&lt;/p&gt;
&lt;p&gt;These are hooked up in a chain, so that other parts importing &lt;em&gt;IProductRepository&lt;/em&gt; will be given the cache, while the cache itself imports the underlying repository.&lt;/p&gt;
&lt;p&gt;The convention that applies to these types is that they export their implemented interfaces.&lt;/p&gt;
&lt;pre&gt;    public interface IProductRepository {
        Product GetById(int id);
    }

    [Export("impl", typeof(IProductRepository))]
    class RemoteProductRepository : IProductRepository { ... }

    class ProductCache : IProductRepository {
        public ProductCache([Import("impl")] IProductRepository impl) { ... }
    }
&lt;/pre&gt;
&lt;p&gt;The named export and import ensure that only the &lt;em&gt;ProductCache&lt;/em&gt; sees the decorated repository.&lt;/p&gt;
&lt;h3&gt;Changing export metadata to customise behavior&lt;/h3&gt;
&lt;p&gt;The &lt;em&gt;TaskRunner&lt;/em&gt; component imports task components that it runs periodically. Metadata is used to determine the frequency at which the task runs.&lt;/p&gt;
&lt;pre&gt;    public interface ITask {
        void Run();
    }

    class TaskRunner : ITaskRunner {
        public TaskRunner(IEnumerable&amp;lt;Lazy&amp;lt;ITask,ITaskFrequency&amp;gt;&amp;gt; tasks) { ... }
    }
&lt;/pre&gt;
&lt;p&gt;Most tasks run hourly, so this is the default by convention.&lt;/p&gt;
&lt;pre&gt;    registrationBuilder.ForTypesDerivedFrom&amp;lt;ITask&amp;gt;()
        .Export&amp;lt;ITask&amp;gt;(x =&amp;gt; x.AddMetadata(&amp;ldquo;Frequency&amp;rdquo;, 60));
&lt;/pre&gt;
&lt;p&gt;The &lt;em&gt;SendMailTask&lt;/em&gt; runs every 5 minutes and uses an override to specify this.&lt;/p&gt;
&lt;pre&gt;     [Export(typeof(ITask)), ExportMetadata("Frequency", 5)]
    class SendMailTask : ITask { ... }
&lt;/pre&gt;
&lt;h3&gt;Selecting a shorter constructor&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;By default&lt;/strong&gt; a part configured with &lt;em&gt;RegistrationBuilder&lt;/em&gt; will use the constructor with the most parameters. In this example, the longer constructor is for unit testing purposes only, so the shorter constructor is marked with an attribute.&lt;/p&gt;
&lt;pre&gt;    class MyPart {
        public MyPart(IFoo foo, IBarTestStub bar) { }

        [ImportingConstructor]
        public MyPart(IFoo foo) { }
    }
&lt;/pre&gt;
&lt;h3&gt;Changing the contract name of an import for explicit wiring&lt;/h3&gt;
&lt;p&gt;If a property is selected as an import by convention, an &lt;em&gt;Import&lt;/em&gt; attribute can be applied to the property to override the contract name or other facet of the &lt;em&gt;ImportDefinition&lt;/em&gt;. This is useful to implement explicit wiring.&lt;/p&gt;
&lt;pre&gt;    class MyPart {
        [Import("impl")]
        public IFoo Foo { get; set; }
    }

    class Foo1 : IFoo { }

    [Export("impl", typeof(IFoo))]
    class Foo2 : IFoo { }
&lt;/pre&gt;
&lt;p&gt;Here the export and import attributes specify names so that the &lt;em&gt;Foo&lt;/em&gt; import on &lt;em&gt;MyPart&lt;/em&gt; will be provided with a &lt;em&gt;Foo2&lt;/em&gt; instance.&lt;/p&gt;
&lt;h3&gt;Opting out&lt;/h3&gt;
&lt;p&gt;If a type that would otherwise be matched by a rule should not be used as a part, it can be marked with the &lt;em&gt;PartNotDiscoverable&lt;/em&gt; attribute:&lt;/p&gt;
&lt;pre&gt;    [PartNotDiscoverable]
    class MyPart {&amp;hellip; }
&lt;/pre&gt;
&lt;h3&gt;Diagnostics&lt;/h3&gt;
&lt;p&gt;Whenever a rule is overridden by a source-level attribute, you can find a diagnostic message in the debugger trace output. This helps keep track of where the exceptions to the rules are. The message looks like:&lt;/p&gt;
&lt;pre&gt;    A convention that would apply to member A of type B has been overridden
    by attributes applied in the source file.&lt;/pre&gt;
&lt;h2&gt;Conclusions&lt;/h2&gt;
&lt;p&gt;When using conventions to register parts in MEF, rules can be kept clean and simple by using the standard MEF attributes to override rules where necessary.&lt;/p&gt;
&lt;p&gt;We hope you enjoy working with the new preview; we deeply value your feedback and would love to hear about your experiences via the &lt;a href="http://mef.codeplex.com/discussions"&gt;Discussion Forum&lt;/a&gt; or &lt;a href="http://mef.codeplex.com/workitem/list/basic"&gt;Issue Tracker&lt;/a&gt; on the MEF developer preview site.&lt;/p&gt;
&lt;p&gt;Coming up on this blog we&amp;rsquo;ll explore the other major addition to MEF in version 2 &amp;ndash; composition scoping.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;&lt;em&gt;&lt;a href="http://mef.codeplex.com/releases/view/75766"&gt;Download MEF 2 Preview 4&lt;/a&gt; from the CodePlex site.&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10233807" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/bclteam/archive/tags/MEF/">MEF</category><category domain="http://blogs.msdn.com/b/bclteam/archive/tags/-NET+Framework+4-5+Preview/">.NET Framework 4.5 Preview</category></item><item><title>Getting started with convention-based part registration in MEF 2 [Nick]</title><link>http://blogs.msdn.com/b/bclteam/archive/2011/11/01/getting-started-with-convention-based-part-registration-in-mef-version-2.aspx</link><pubDate>Tue, 01 Nov 2011 18:14:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10232164</guid><dc:creator>BCL Team</dc:creator><slash:comments>4</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/bclteam/rsscomments.aspx?WeblogPostID=10232164</wfw:commentRss><comments>http://blogs.msdn.com/b/bclteam/archive/2011/11/01/getting-started-with-convention-based-part-registration-in-mef-version-2.aspx#comments</comments><description>&lt;p&gt;&lt;strong&gt;&lt;em&gt;This post discusses features in the &lt;a href="http://blogs.msdn.com/b/bclteam/archive/2011/10/27/what-s-new-in-mef-version-2-preview-4.aspx"&gt;preview version of MEF&lt;/a&gt;, and some details may change between now and the full release. &lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;MEF &amp;lsquo;version 1&amp;rsquo; uses attributes to describe how a type should be handled for composition purposes.&lt;/p&gt;
&lt;pre&gt;    [Export, PartCreationPolicy(CreationPolicy.NonShared)]
    public class HomeController :  Controller
    {
        [ImportingConstructor]
        public HomeController(/* Dependencies here */) { &amp;hellip; }
        public ActionResult Index() { &amp;hellip; }
    }
&lt;/pre&gt;
&lt;p&gt;Attributes are a good fit for plug-in development when building extensible applications, and we haven't changed any of this experience in the new version. Attributes are still a great way to unambiguously mark-up types for composition.&lt;/p&gt;
&lt;p&gt;Planning MEF &amp;lsquo;version 2&amp;rsquo; we observed that in large MEF-based applications, only a small proportion of imports and exports are actually extensibility related. A large amount of composition happens to support the internal architecture of the application itself. In many cases, applications that use MEF don&amp;rsquo;t provide a third-party plug-in model at all, and use MEF purely as a way to bring the benefits of loosely-coupled architecture to monolithic apps.&lt;/p&gt;
&lt;p&gt;In the context of a single application, it is much easier to set and communicate rules about how parts should be written, loosening up the need to explicitly specify every detail of every part.&lt;/p&gt;
&lt;p&gt;In the example above, if &lt;em&gt;all&lt;/em&gt; controllers are exported, all have the &lt;em&gt;NonShared&lt;/em&gt; creation policy, and all use a single constructor to receive dependencies, then it is in some ways harmful to repeat that information using attributes on every single controller class. Given these &amp;lsquo;norms&amp;rsquo; for a controller, a programmer working in a structured application should be able to write:&lt;/p&gt;
&lt;pre&gt;    public class HomeController :  Controller
    {
        public HomeController(/* Dependencies here */) { &amp;hellip; }
        public ActionResult Index() { &amp;hellip; }
    }
&lt;/pre&gt;
&lt;p&gt;&amp;hellip;and have the composition aspects inferred automatically. Less repetition leads to more readable code, less overall lines of code and fewer opportunities to make mistakes.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;RegistrationBuilder&lt;/em&gt; is a new MEF feature coming in .NET 4.5 that provides exactly this kind of experience. Using &lt;em&gt;RegistrationBuilder&lt;/em&gt;, the rules defining controller parts look like:&lt;/p&gt;
&lt;pre&gt;    var conventions = new RegistrationBuilder();
    conventions.ForTypesDerivedFrom&amp;lt;Controller&amp;gt;()
        .Export()
        .SetCreationPolicy(CreationPolicy.NonShared);
&lt;/pre&gt;
&lt;p&gt;Notice that the rule doesn&amp;rsquo;t say anything about how to find types that derive from &lt;em&gt;Controller&lt;/em&gt;. Catalogs still play the role of locating types, while &lt;em&gt;RegistrationBuilder&lt;/em&gt; rules replace the attribute syntax. So, to apply these rules to all types in an assembly, an &lt;em&gt;AssemblyCatalog&lt;/em&gt; is used:&lt;/p&gt;
&lt;pre&gt;    Assembly controllersAssembly = // &amp;hellip;
    var catalog = new AssemblyCatalog(controllersAssembly, conventions);
    var container = new CompositionContainer(catalog);

&lt;/pre&gt;
&lt;p&gt;Notice the additional constructor parameter accepted by the catalog. All of the familiar MEF catalog types have been updated in the new version to support &lt;em&gt;RegistrationBuilder&lt;/em&gt; conventions.&lt;/p&gt;
&lt;h2&gt;Building Conventions&lt;/h2&gt;
&lt;p&gt;Using &lt;em&gt;RegistrationBuilder&lt;/em&gt; has two aspects:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Identifying types that should be considered parts; and,&lt;/li&gt;
&lt;li&gt;Configuring types for use as parts.&lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;Identifying Parts&lt;/h2&gt;
&lt;p&gt;Each rule is defined by calling one of the three &lt;em&gt;For*()&lt;/em&gt; methods on &lt;em&gt;RegistrationBuilder&lt;/em&gt; to specify which types the rule will apply to.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;ForType&amp;lt;T&amp;gt;()&lt;/strong&gt; &amp;mdash; selects the single type &lt;em&gt;T&lt;/em&gt;. For example &lt;em&gt;ForType&amp;lt;HomeController&amp;gt;()&lt;/em&gt; would set up a rule for the concrete &lt;em&gt;HomeController&lt;/em&gt; type.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;ForTypesDerivedFrom&amp;lt;T&amp;gt;()&lt;/strong&gt; &amp;mdash; selects types assignable, but not equal to, a contract type &lt;em&gt;T&lt;/em&gt;. This may be a base class or an interface. The example rule for identifying controllers earlier in this article uses this mechanism.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;ForTypesMatching(Predicate&amp;lt;Type&amp;gt; predicate)&lt;/strong&gt; &amp;mdash; selects types that match a Boolean selector. For example, &lt;em&gt;ForTypesMatching(t =&amp;gt; t.Name.EndsWith("Repository"))&lt;/em&gt; will select all types whose name ends with the word &amp;ldquo;Repository&amp;rdquo;. This is the most flexible option.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Multiple rules may match the same type. In such cases, as long as the rules don&amp;rsquo;t overlap in an incompatible way, all matching rules are applied.&lt;/p&gt;
&lt;p&gt;The selector methods above return a &lt;em&gt;PartBuilder&lt;/em&gt; that can then be used to configure the matching types for use as parts.&lt;/p&gt;
&lt;h2&gt;Configuring Parts&lt;/h2&gt;
&lt;p&gt;Rules can be used to configure all aspects of a MEF part:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Exported interfaces and properties, with metadata&lt;/li&gt;
&lt;li&gt;Importing constructors, constructor parameters and properties&lt;/li&gt;
&lt;li&gt;Part creation policy&lt;/li&gt;
&lt;li&gt;Part metadata&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;Exports&lt;/h3&gt;
&lt;p&gt;Exports can be configured at the type declaration/interface level, or via properties in the case of property exports.&lt;/p&gt;
&lt;p&gt;At the level of the part type itself, the concrete type of the part can be exported (in this case &lt;em&gt;MainWindow&lt;/em&gt;):&lt;/p&gt;
&lt;pre&gt;    conventions.ForType&amp;lt;MainWindow&amp;gt;()
        .Export()

&lt;/pre&gt;
&lt;p&gt;Or, more commonly, one or more of its interfaces will be exported:&lt;/p&gt;
&lt;pre&gt;    conventions.ForType&amp;lt;MainWindow&amp;gt;()
        .Export&amp;lt;IView&amp;gt;();
&lt;/pre&gt;
&lt;p&gt;Multiple interfaces can be exported using a filter:&lt;/p&gt;
&lt;pre&gt;    conventions.ForType&amp;lt;MainWindow&amp;gt;()
        .ExportInterfaces(i =&amp;gt; i.IsPublic);

&lt;/pre&gt;
&lt;p&gt;Overloads exist for configuring the export with a contract name or with metadata:&lt;/p&gt;
&lt;pre&gt;    conventions.ForType&amp;lt;MainWindow&amp;gt;()
        .Export&amp;lt;IView&amp;gt;(x =&amp;gt; x.AddMetadata("Name", "Main"))
&lt;/pre&gt;
&lt;p&gt;Properties can be exported using a similar syntax. If the concrete type is specified, properties can be selected using a Linq expression:&lt;/p&gt;
&lt;pre&gt;    conventions.ForType&amp;lt;MainWindow&amp;gt;()
        .ExportProperty(mw =&amp;gt; mw.Notifier);
&lt;/pre&gt;
&lt;p&gt;When the concrete type is not known, for example with &lt;em&gt;ForTypesMatching()&lt;/em&gt;, properties can be exported by selecting them:&lt;/p&gt;
&lt;pre&gt;    conventions.ForTypesMatching(t =&amp;gt; t.Namespace == "MyApp.Windows")
        .ExportProperties(pi =&amp;gt; pi.IsPublic);

&lt;/pre&gt;
&lt;p&gt;Multiple export-related configuration rules on the same part are additive, so a type can export several contracts:&lt;/p&gt;
&lt;pre&gt;    conventions.ForType&amp;lt;MainWindow&amp;gt;()
        .Export&amp;lt;IView&amp;gt;()
        .Export&amp;lt;ICloseable&amp;gt;();
&lt;/pre&gt;
&lt;h3&gt;Imports&lt;/h3&gt;
&lt;p&gt;Imports are specified either at the constructor or at the property level.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;By default&lt;/strong&gt;, the &lt;em&gt;RegistrationBuilder&lt;/em&gt; will select the public constructor with the most parameters as the importing constructor.&lt;/p&gt;
&lt;p&gt;To select a different constructor, the &lt;em&gt;SelectConstructor()&lt;/em&gt; method is used.&lt;/p&gt;
&lt;pre&gt;    conventions.ForTypesDerivedFrom&amp;lt;IView&amp;gt;()
        .SelectConstructor(ctors =&amp;gt;
            ctors.Min(ctor =&amp;gt; ctor.GetParameters().Length));
&lt;/pre&gt;
&lt;p&gt;When the concrete type of the part is known at configuration time, the constructor can be selected using strongly-typed syntax:&lt;/p&gt;
&lt;pre&gt;    conventions.ForType&amp;lt;MainWindow&amp;gt;()
        .SelectConstructor(pb =&amp;gt; new MainWindow(pb.Import&amp;lt;ILogger&amp;gt;()));
&lt;/pre&gt;
&lt;p&gt;&lt;strong&gt;By default&lt;/strong&gt;, any constructor parameters or imported properties of an enumerable or collection type will be considered to &lt;em&gt;&amp;ldquo;Import Many&amp;rdquo;&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;The syntax for performing property imports mirrors the syntax described for property exports previously.&lt;/p&gt;
&lt;h3&gt;Part Creation Policy&lt;/h3&gt;
&lt;p&gt;&lt;strong&gt;By default&lt;/strong&gt;, parts configured by &lt;em&gt;RegistrationBuilder&lt;/em&gt; will use the standard MEF &lt;em&gt;CreationPolicy.Any&lt;/em&gt; setting. In normal use, this will boil down to &amp;lsquo;single instance per container&amp;rsquo; sharing, unless the part is created using an &lt;em&gt;ExportFactory&amp;lt;T&amp;gt;&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;To select the creation policy, use the &lt;em&gt;SetCreationPolicy()&lt;/em&gt; method:&lt;/p&gt;
&lt;pre&gt;    conventions.ForTypesDerivedFrom&amp;lt;Controller&amp;gt;()
        .SetCreationPolicy(CreationPolicy.NonShared);
&lt;/pre&gt;
&lt;p&gt;(Note, the ASP.NET MVC integration also included in the preview interprets &lt;em&gt;CreationPolicy.Any&lt;/em&gt; and &lt;em&gt;CreationPolicy.Shared&lt;/em&gt; to mean &amp;lsquo;single instance per HTTP request.&amp;rsquo; To make a part use &amp;lsquo;single instance per application&amp;rsquo; sharing under ASP.NET MVC, you need to apply the &lt;em&gt;ApplicationShared&lt;/em&gt; attribute to the part.)&lt;/p&gt;
&lt;h3&gt;Part Metadata&lt;/h3&gt;
&lt;p&gt;Part metadata is useful when filtering parts in customized catalogs, or when setting up a &lt;em&gt;CompositionScopeDefinition&lt;/em&gt;. Part metadata can be added explicitly, as in:&lt;/p&gt;
&lt;pre&gt;    conventions.ForType&amp;lt;OutputWindow&amp;gt;()
        .AddMetadata("Mode", "Debug");
&lt;/pre&gt;
&lt;p&gt;Or, it can be calculated from the type:&lt;/p&gt;
&lt;pre&gt;    conventions.ForType&amp;lt;OutputWindow&amp;gt;()
        .AddMetadata("Mode", t =&amp;gt; GetMode(t));
&lt;/pre&gt;
&lt;h2&gt;Overriding Rules&lt;/h2&gt;
&lt;p&gt;Inevitably, there are exceptions to every rule. In these situations, the MEF attributes can often be used to override the rules on a case-by-case basis. This is the topic of an upcoming post &amp;ndash; stay tuned!&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;&lt;em&gt;&lt;a href="http://mef.codeplex.com/releases/view/75766"&gt;Download MEF 2 Preview 4&lt;/a&gt; from the CodePlex site.&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10232164" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/bclteam/archive/tags/MEF/">MEF</category><category domain="http://blogs.msdn.com/b/bclteam/archive/tags/-NET+Framework+4-5+Preview/">.NET Framework 4.5 Preview</category></item><item><title>What’s new in MEF 2 Preview 4? [Alok, Nick]</title><link>http://blogs.msdn.com/b/bclteam/archive/2011/10/27/what-s-new-in-mef-version-2-preview-4.aspx</link><pubDate>Thu, 27 Oct 2011 23:15:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10230814</guid><dc:creator>BCL Team</dc:creator><slash:comments>1</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/bclteam/rsscomments.aspx?WeblogPostID=10230814</wfw:commentRss><comments>http://blogs.msdn.com/b/bclteam/archive/2011/10/27/what-s-new-in-mef-version-2-preview-4.aspx#comments</comments><description>&lt;p&gt;The MEF team has been quietly at work for some time getting the finishing touches on another developer preview. You can &lt;a href="http://mef.codeplex.com/releases/view/75766"&gt;download&lt;/a&gt; the new source and .NET 4.0-compatible binaries from the Codeplex site.&lt;/p&gt;
&lt;p&gt;This preview is another step towards the next supported release, which will be made as part of .NET 4.5.&lt;/p&gt;
&lt;p&gt;Highlights of the new version are:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Support for generic parts&lt;/li&gt;
&lt;li&gt;A new convention-based registration API (attributes optional!)&lt;/li&gt;
&lt;li&gt;New scoping features that use &lt;em&gt;ExportFactory&lt;/em&gt; and &lt;em&gt;CompositionScopeDefinition&lt;/em&gt;&lt;/li&gt;
&lt;li&gt;Integrated support for MEF composition in &lt;a href="http://asp.net/mvc"&gt;ASP.NET MVC&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;Diagnostics improvements&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;Open generic parts&lt;/h2&gt;
&lt;p&gt;Open generic types can now be used as parts. For example, if you are using the Generic Repository pattern, you may use &lt;em&gt;IRepository&amp;lt;T&amp;gt;&lt;/em&gt; as a contract:&lt;/p&gt;
&lt;pre&gt;public interface IRepository&amp;lt;T&amp;gt; where T : class
{
    T FindById(int id);
}
&lt;/pre&gt;
&lt;p&gt;Other parts then import this contract using closed types like &lt;em&gt;IRepository&amp;lt;Customer&amp;gt;&lt;/em&gt;:&lt;/p&gt;
&lt;pre&gt;[Export]
public class CustomersWindow :  Window
{
    [ImportingConstructor]
    public CustomerWindow(IRepository&amp;lt;Customer&amp;gt; customers)
    {
        // &amp;hellip; use customers
&lt;/pre&gt;
&lt;p&gt;Rather than create a specific &lt;em&gt;CustomerRepository&lt;/em&gt; class, and a similar implementation for other kinds of repository, the repository interface can be exported on a generic type:&lt;/p&gt;
&lt;pre&gt;[Export(typeof(IRepository&amp;lt;&amp;gt;))]
public class EntityFrameworkRepository&amp;lt;T&amp;gt; : IRepository&amp;lt;T&amp;gt; where T : class
{
    // &amp;hellip; generic repository implementation
&lt;/pre&gt;
&lt;p&gt;Open generic parts reduce the effort required to implement many common scenarios.&lt;/p&gt;
&lt;h2&gt;Convention-based part registration&lt;/h2&gt;
&lt;p&gt;The previous MEF release was optimized for third-party extensibility scenarios, where explicit annotation of parts with attributes makes a lot of sense. When the entire application is under the control of one group of developers, applying attributes to describe parts can be redundant and repetitive.&lt;/p&gt;
&lt;p&gt;For example, every class that derives from &lt;em&gt;Window&lt;/em&gt; in an application might have an &lt;em&gt;Export&lt;/em&gt; attribute applied:&lt;/p&gt;
&lt;pre&gt;[Export]
class CustomersWindow : Window { &amp;hellip; }
&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;RegistrationBuilder&lt;/em&gt; is a class added in the new release that allows a set of rules (&amp;lsquo;conventions&amp;rsquo;) to be defined that map types to parts, without the need for attributes.&lt;/p&gt;
&lt;pre&gt;var rb = new RegistrationBuilder();
rb.ForTypesDerivedFrom&amp;lt;Window&amp;gt;().Export();
&lt;/pre&gt;
&lt;p&gt;The standard MEF catalogs accept a &lt;em&gt;RegistrationBuilder&lt;/em&gt; as a constructor parameter, and will apply the rules defined in the registration builder to the types included in the catalog:&lt;/p&gt;
&lt;pre&gt;var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly(), rb);
&lt;/pre&gt;
&lt;p&gt;&lt;em&gt;RegistrationBuilder&lt;/em&gt; is available in &lt;em&gt;System.ComponentModel.Composition.Registration&lt;/em&gt;.&lt;/p&gt;
&lt;h2&gt;Composition scoping enhancements&lt;/h2&gt;
&lt;p&gt;In the first version of MEF, part instances could be either shared or per-importer, but it was much harder to control scope and lifetime in a more fine-grained way. Often it is desirable to configure and manage parts as a group to handle some kind of unit of work &amp;ndash; a web request, processing a message or managing a single visual element like a WPF view and &lt;em&gt;ViewModel&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;The new MEF release makes it easier to control the lifetime and sharing of parts. This example shows how the new scoping support can be used to isolate the parts used for processing 'messages' &amp;mdash; the basic pattern applies to many scenarios.&lt;/p&gt;
&lt;pre&gt;[Export]
public class DataConnection
{
}
 
[Export]
public class MessageHandler
{
    [ImportingConstructor]
    public MessageHandler(DataConnection dataConnection) { &amp;hellip; }

    // HandleMessage(Message m) omitted
}
&lt;/pre&gt;
&lt;p&gt;The two 'skeleton' parts above work together to process a network message of some kind. Each time a message handler is created, it will be initialized with a DataConnection that it will use to make changes in response to the message.&lt;/p&gt;
&lt;p&gt;More importantly, other dependencies of &lt;em&gt;MessageHandler&lt;/em&gt; (not shown) should share the same &lt;em&gt;DataConnection&lt;/em&gt;. &lt;em&gt;MessageHandler&lt;/em&gt;s processing different messages should get different &lt;em&gt;DataConnection&lt;/em&gt;s. Any of these parts may also have dependencies that are global, i.e. common to all scopes.&lt;/p&gt;
&lt;pre&gt;[Export]
public class MessageListener
{
    [ImportingConstructor]
    public MessageListener(ExportFactory&amp;lt;MessageHandler&amp;gt; handlerFactory) { &amp;hellip; }
 
    public void ProcessRequest()
    {
        var message = GetNextMessage();
        using (var handler = _handlerFactory.CreateExport())
            handler.HandleMessage(message);
    }
}
&lt;/pre&gt;
&lt;p&gt;The implementation of &lt;em&gt;MessageListener&lt;/em&gt; may be familiar to users of MEF in Silverlight 4. The &lt;em&gt;ExportFactory&amp;lt;T&amp;gt;&lt;/em&gt; type allows the &lt;em&gt;MessageListener&lt;/em&gt; to create a new message handler for each message.&lt;/p&gt;
&lt;p&gt;Now, by default, this won&amp;rsquo;t enable any kind of scoping around the individual message listeners &amp;mdash; they&amp;rsquo;ll all share the same scope (and &lt;em&gt;DataConnection&lt;/em&gt;) as the &lt;em&gt;MessageListener&lt;/em&gt;.&lt;/p&gt;
&lt;p&gt;To describe the scoping we want, the container needs to be created with a &lt;em&gt;CompositionScopeDefinition&lt;/em&gt; in place of a &lt;em&gt;ComposablePartCatalog&lt;/em&gt;:&lt;/p&gt;
&lt;pre&gt;var globalParts = new TypeCatalog(typeof(MessageListener));
var perMessageParts = new TypeCatalog(typeof(MessageHandler), typeof(DbConnection));
var scopeDefinition = new CompositionScopeDefinition(globalParts,
            new[] { new CompositionScopeDefinition(perMessageParts, null)});

var container = new CompositionContainer(scopeDefinition);
var listener = container.GetExportedValue&amp;lt;GlobalRequestManager&amp;gt;();
listener.HandleMessage();
listener.HandleMessage();
&lt;/pre&gt;
&lt;p&gt;Every time &lt;em&gt;HandleMessage()&lt;/em&gt; is called, new scoped instances of &lt;em&gt;MessageHandler&lt;/em&gt; and &lt;em&gt;DataConnection&lt;/em&gt; are created and released.&lt;/p&gt;
&lt;p&gt;&lt;em&gt;CompositionScopeDefinition&lt;/em&gt; is available in the &lt;em&gt;System.ComponentModel.Composition.Hosting&lt;/em&gt; namespace.&lt;/p&gt;
&lt;h3&gt;Composition provider for ASP.NET MVC&lt;/h3&gt;
&lt;p&gt;Simplifying the use of MEF in web applications is a core goal of the new release. To further this aim, we are supplying functionality that integrates MEF into ASP.NET MVC, to allow controllers and other MVC types to participate in composition.&lt;/p&gt;
&lt;p&gt;To use this feature, reference the &lt;em&gt;System.ComponentModel.Composition.Web.Mvc&lt;/em&gt; assembly in your ASP.NET MVC project. All configuration is handled automatically &amp;mdash; to create parts, add them to a &lt;em&gt;Parts&lt;/em&gt; namespace (folder) under the MVC site:&lt;/p&gt;
&lt;pre&gt;namespace FabrikamBooks.Parts
{
    class TraceLogger : ILogger { &amp;hellip; }
&lt;/pre&gt;
&lt;p&gt;Just by being under the Parts folder, the class will automatically &amp;lsquo;export&amp;rsquo; all of its implemented interfaces. The longest constructor on the class will be treated as its importing constructor. No attributes are required, unless you want to override the inbuilt defaults.&lt;/p&gt;
&lt;p&gt;Controllers simply take dependencies on parts through their constructors:&lt;/p&gt;
&lt;pre&gt;class HomeController : Controller
{
    // MEF will automatically supply TraceLogger
    public HomeController(ILogger logger) { &amp;hellip; }
&lt;/pre&gt;
&lt;p&gt;The composition provider implements a set of defaults that we feel are sensible for most web applications. These defaults can be overridden by applying attributes to parts. Advanced users can still set up MEF &amp;lsquo;by hand&amp;rsquo; to meet more specific goals.&lt;/p&gt;
&lt;p&gt;The downloadable binaries for this feature are built against ASP.NET MVC version 3; if you want to rebuild the assemblies from source, you'll need to get ASP.NET MVC separately. To maintain a flexible release schedule as this component evolves, we anticipate delivering binaries via &lt;a href="http://nuget.org"&gt;NuGet&lt;/a&gt; rather than the .NET Framework SDK.&lt;/p&gt;
&lt;h2&gt;Diagnostics improvements&lt;/h2&gt;
&lt;p&gt;Providing good diagnostic support in a framework as dynamic and flexible as MEF is a challenge, and is something that we expect to go on improving over time.&lt;/p&gt;
&lt;p&gt;In this release, two key improvements have been made to diagnostics in MEF.&lt;/p&gt;
&lt;h3&gt;CompositionOptions.DisableSilentRejection&lt;/h3&gt;
&lt;p&gt;MEF&amp;rsquo;s roots in extensibility make it more tolerant of composition problems than other similar frameworks. Parts with missing dependencies are identified and excluded from composition, which makes diagnostics hard in some circumstances.&lt;/p&gt;
&lt;p&gt;When constructing a &lt;em&gt;CompositionContainer&lt;/em&gt; in the new MEF version, flags can be passed controlling this and other behaviors. Specifying &lt;em&gt;CompositionOptions.DisableSilentRejection&lt;/em&gt; will cause exceptions to be thrown when any composition problem occurs.&lt;/p&gt;
&lt;pre&gt;var container = new CompositionContainer(
    catalog, CompositionOptions.DisableSilentRejection);
&lt;/pre&gt;
&lt;p&gt;It is recommended that most users building non-third-party-extensible applications specify this flag. It is set by default when using the ASP.NET MVC composition provider described previously.&lt;/p&gt;
&lt;h3&gt;Better exception messages&lt;/h3&gt;
&lt;p&gt;Finally, the exception message text in the first version of MEF can be complex and verbose in some situations. The new release improves the way exception messages are formatted, presenting the most important information up-front.&lt;/p&gt;
&lt;h2&gt;Moving forward&lt;/h2&gt;
&lt;p&gt;&lt;strong&gt;Subscribe to this blog&lt;/strong&gt; for examples and more detailed documentation on the new features.&lt;/p&gt;
&lt;p&gt;We&amp;rsquo;re looking forward to your feedback on this release. As always, you can get in touch with the team through this blog or at the MEF Codeplex site&amp;rsquo;s &lt;a href="http://mef.codeplex.com/workitem/list/basic"&gt;issue list&lt;/a&gt; and &lt;a href="http://mef.codeplex.com/discussions"&gt;discussion forum&lt;/a&gt;.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10230814" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/bclteam/archive/tags/MEF/">MEF</category><category domain="http://blogs.msdn.com/b/bclteam/archive/tags/-NET+Framework+4-5+Preview/">.NET Framework 4.5 Preview</category></item><item><title>Porting existing .NET code to Metro style apps [Wes]</title><link>http://blogs.msdn.com/b/bclteam/archive/2011/10/03/porting-existing-net-code-to-metro-style-apps.aspx</link><pubDate>Tue, 04 Oct 2011 04:25:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10219543</guid><dc:creator>BCL Team</dc:creator><slash:comments>5</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/bclteam/rsscomments.aspx?WeblogPostID=10219543</wfw:commentRss><comments>http://blogs.msdn.com/b/bclteam/archive/2011/10/03/porting-existing-net-code-to-metro-style-apps.aspx#comments</comments><description>&lt;p&gt;As many of you know at &lt;a href="http://www.buildwindows.com/"&gt;//build&lt;/a&gt; we announced that there will be a new .NET target framework for Metro style apps. To learn more about the goals of this new target framework I encourage you to watch Krzystzof Cwalina&amp;rsquo;s build talk "&lt;a href="http://channel9.msdn.com/Events/BUILD/BUILD2011/TOOL-930C"&gt;A .NET developer's view of Windows 8 app development&lt;/a&gt;".&lt;/p&gt;
&lt;p&gt;One of the things we know people want to do is reuse existing .NET code but due to the constraints on Metro style apps it is not possible to directly reuse existing .NET class libraries nor is it always possible to simply recompile existing code. We realize this is going to be a pain point for many current .NET developers so we are working on a guide at the &lt;a href="http://msdn.microsoft.com/en-us/library/windows/apps/br230302.aspx"&gt;.NET for Metro style apps overview page&lt;/a&gt; which will assist developers in translating their existing .NET skill set into the Metro style apps world. Sometimes that means explaining why something was removed and other times it means giving another .NET or WinRT API to call instead. Today the page is limited but we are actively working on it internally to update it with more data for Beta and RTM.&lt;/p&gt;
&lt;p&gt;For a demo of the kind of things you are likely to run into while porting code I suggest watching Daniel Plaisted&amp;rsquo;s build talk "&lt;a href="http://channel9.msdn.com/Events/BUILD/BUILD2011/TOOL-790C"&gt;Bringing existing managed code into Metro style apps&lt;/a&gt;".&lt;/p&gt;
&lt;p&gt;While we are looking at many forms of feedback we would greatly appreciate any feedback on issues you run into while porting existing .NET code to Metro style apps. Please leave feedback in the comments or on the &lt;a href="http://social.msdn.microsoft.com/Forums/en-US/winappswithcsharp/threads"&gt;forums&lt;/a&gt;.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10219543" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/bclteam/archive/tags/-NET+for+Metro+style+apps/">.NET for Metro style apps</category></item><item><title>Memory Mapped File Quirks [Greg]</title><link>http://blogs.msdn.com/b/bclteam/archive/2011/06/06/memory-mapped-file-quirks.aspx</link><pubDate>Mon, 06 Jun 2011 20:56:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10171770</guid><dc:creator>BCL Team</dc:creator><slash:comments>2</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/bclteam/rsscomments.aspx?WeblogPostID=10171770</wfw:commentRss><comments>http://blogs.msdn.com/b/bclteam/archive/2011/06/06/memory-mapped-file-quirks.aspx#comments</comments><description>&lt;p&gt;Memory mapped files are segments of virtual memory that are directly mapped to a physical file on disk, byte-by-byte. This technology has a number of benefits over traditional stream based I/O, such as performance during random access to large files, or the ability to share the mapped memory between different threads and processes. The .NET framework provides built-in support for memory mapped files starting from version 4. In most cases using memory mapped files in .NET is as easy as using traditional files streams: just map a file into the memory, open a seekable memory stream and use it as if it was a normal file while enjoying all the performance benefits. However, there are some subtle, but important differences. One of them is that memory mapped file views must always be aligned at the boundaries of the system&amp;rsquo;s virtual memory pages. An important consequence is that:&lt;/p&gt;
&lt;p style="border: 1px solid black; padding: 10px; margin: 5px 40px;"&gt;Compared to the size of the underlying file on disk, the size of a memory mapped view stream is always rounded up towards a multiple of the system&amp;rsquo;s virtual memory page size. You must take care to differentiate between useful data and junk bytes used to fill up the space.&lt;/p&gt;
&lt;h2&gt;A little background&lt;/h2&gt;
&lt;p&gt;A memory mapped file is a continuous chunk of memory in a process address space that has a direct byte-by-byte mapping to an external resource. Typically, such resource is a data file on the physical hard drive. However, it is also possible to represent device memory or any other OS object that can be accessed via a file handle as a memory mapped file structure. In Windows, memory mapped files can also be backed by the system page file rather than by a separate file system object.&lt;/p&gt;
&lt;p&gt;In Windows, &lt;a href="http://msdn.microsoft.com/en-us/library/ms810613.aspx"&gt;managing memory mapped files&lt;/a&gt; has been supported for a while (see the &lt;a href="http://msdn.microsoft.com/en-us/library/aa366781.aspx#file_mapping_functions"&gt;function reference&lt;/a&gt;). The .NET framework &lt;a href="http://msdn.microsoft.com/en-us/library/dd997372.aspx"&gt;natively supports&lt;/a&gt; this technology starting from version 4.0 through the types in the &lt;a href="http://msdn.microsoft.com/en-us/library/dd267568.aspx"&gt;&lt;code&gt;System.IO.MemoryMappedFiles&lt;/code&gt; namespace&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;In .NET you can create a memory mapping either for an existing file on the physical hard drive by specifying its path, or for an existing mapping by referring to the map name. Alternatively, you can create a new memory mapped file and have the system automatically manage a temporary file on disk to back it up. The temp file will be automatically deleted when you dispose of the memory mapped file; this is particularly useful when using memory mapped files for inter-process communication rather than for data persistence. In any case you need to use one of the static methods in the &lt;a href="http://msdn.microsoft.com/en-us/library/system.io.memorymappedfiles.memorymappedfile.aspx"&gt;&lt;code&gt;MemoryMappedFile&lt;/code&gt; class&lt;/a&gt; to create a memory map instance.&lt;/p&gt;
&lt;p&gt;On the OS level, in order to actually read data from or write data to a &lt;a href="http://msdn.microsoft.com/en-us/library/aa366556.aspx"&gt;file mapping&lt;/a&gt; you need to first &lt;a href="http://msdn.microsoft.com/en-us/library/aa366546.aspx"&gt;create&lt;/a&gt; a view (projection) of that map into your process. Luckily, .NET handles this for you and all you need to do is to create either a &lt;a href="http://msdn.microsoft.com/en-us/library/system.io.memorymappedfiles.memorymappedviewaccessor.aspx"&gt;&lt;code&gt;MemoryMappedViewAccessor&lt;/code&gt;&lt;/a&gt; or a &lt;a href="http://msdn.microsoft.com/en-us/library/system.io.memorymappedfiles.memorymappedviewstream.aspx"&gt;&lt;code&gt;MemoryMappedViewStream&lt;/code&gt;&lt;/a&gt; using the &lt;a href="http://msdn.microsoft.com/en-us/library/system.io.memorymappedfiles.memorymappedfile.createviewaccessor.aspx"&gt;&lt;code&gt;CreateViewAccessor&lt;/code&gt;&lt;/a&gt; or &lt;a href="http://msdn.microsoft.com/en-us/library/system.io.memorymappedfiles.memorymappedfile.createviewstream.aspx"&gt;&lt;code&gt;CreateViewStream&lt;/code&gt;&lt;/a&gt; methods respectively. You can then use the accessor or the stream for I/O on the memory mapped file. Particularly when using the stream, the approach is not much different from using a traditional &lt;a href="http://msdn.microsoft.com/en-us/library/system.io.filestream.aspx"&gt;&lt;code&gt;FileStream&lt;/code&gt;&lt;/a&gt;.&lt;/p&gt;
&lt;h2&gt;Subtle differences (A): The map is not quite the same as the source&lt;/h2&gt;
&lt;p&gt;Every technology must be fully understood in order to fully realise the improvements it brings over older technologies, and this is no different for memory mapped files. Although a memory map can be usually understood as a byte-by-byte mapping of the underlying resource (file) there are some subtle, but important cases where this does not apply. It is important to be aware of these cases when working with memory mapped files.&lt;/p&gt;
&lt;p&gt;For instance, recall that NTFS optionally supports both, compression and encryption of files. Even if compression has not been activated, NTFS can also support sparse files. The idea behind sparse files is, in a nutshell, that if a file contains a very large number of consecutive zeros, the file system performs a very simple form of compression that avoids writing out all those zeros to the disk. Instead, just the number of the zeros is written, thus saving disk space without a measurable performance cost. When the zeros are overwritten with other data, the file system replaces those file chunks with normal data segments. All this happens transparently to the layers above the file system. So, when you create a memory mapping of an encrypted, compressed or sparse file, the memory map holds the respectively decrypted, decompressed or inflated content of the file. As a result, the memory page does not correspond to the physical disk file content on a byte-by-byte level. In most cases you do not need to worry about it. However, in some cases this difference may become important, for instance when you want to copy the map contents to a file manually rather than flushing the view, or when you want to use the memory map contents to reason about the size of the file on disk.&lt;/p&gt;
&lt;h2&gt;Subtle differences (B): Where are all those zeros coming from?&lt;/h2&gt;
&lt;p&gt;Another important difference relates to the size or length of the file on disk vs. the size of the memory map. To emphasize the problem, let us consider an example program that reads and displays the contents of a text file that has been mapped to memory:&lt;/p&gt;
&lt;pre class="brush: cs"&gt; 
using System;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Text;
 
 
namespace Microsoft.NetFx.BCL.MSDNBlog {
class MemoryMappedViewStreamLengthDemo {
 
  const String dataFilePath = @"data01.txt";
 
 
  public void Exec() {
 
    using (MemoryMappedFile mmFile = MemoryMappedFile.CreateFromFile(dataFilePath)) {
 
      Stream mmvStream = mmFile.CreateViewStream();
      Console.WriteLine("Stream length: {0}", mmvStream.Length);
            
      using (StreamReader sr = new StreamReader(mmvStream, ASCIIEncoding.ASCII)) {
 
        while (!sr.EndOfStream) {
 
          String line = sr.ReadLine();
          Console.WriteLine("[{0:D4}] \"{1}\"", line.Length, line);
        }
      }            
    }
  }
 
 
  public static void Main(String[] unusedArgs) {
 
    (new MemoryMappedViewStreamLengthDemo()).Exec();
  }
 
}
}
&lt;/pre&gt;
&lt;p&gt;The input file &lt;code&gt;data01.txt&lt;/code&gt; looks like this:&lt;/p&gt;
&lt;pre class="brush: plain"&gt; 
111
222
333
&lt;/pre&gt;
&lt;p&gt;This file is 13 bytes long: 9 bytes are taken up by the digit characters, and 4 more by the invisible carriage return (&lt;code&gt;\r&lt;/code&gt;) and new line (&lt;code&gt;\n&lt;/code&gt;) characters in lines 1 and 2 (line 3 does not have them because there is no new line 4). Here is a hex-binary view of the file:&lt;/p&gt;
&lt;pre class="brush: plain; gutter: false"&gt; 
31  31  31  0D  0A  32  32  32  0D  0A  33  33  33
 1   1   1  \r  \n   2   2   2  \r  \n   3   3   3
&lt;/pre&gt;
&lt;p&gt;So naturally, we expect the following output: (note that &lt;code&gt;ReadLine()&lt;/code&gt; discards the training &lt;code&gt;\r&lt;/code&gt; and &lt;code&gt;\n&lt;/code&gt; characters)&lt;/p&gt;
&lt;pre style="border: 1px solid #E8E8E8; padding: 5px 7px 5px 1px; width: 595px;"&gt;Stream length: 13
&lt;span style="color: #6666d0;"&gt;[0003]&lt;/span&gt; "111"
&lt;span style="color: #6666d0;"&gt;[0003]&lt;/span&gt; "222"
&lt;span style="color: #6666d0;"&gt;[0003]&lt;/span&gt; "333"&lt;/pre&gt;
&lt;p&gt;(Note: the prefix "&lt;code style="color: #6666d0;"&gt;[0003]&lt;/code&gt;" describes the length of each line. It results from the "&lt;code&gt;[{0:D4}]&lt;/code&gt;"-part of the &lt;code&gt;WriteLine&lt;/code&gt; command in the inner loop of the above example program.)&lt;/p&gt;
&lt;p&gt;However, this is not what we get. Instead, we get this (on my machine):&lt;/p&gt;
&lt;pre style="border: 1px solid #E8E8E8; padding: 5px 7px 5px 1px; width: 595px;"&gt;Stream length: 4096
&lt;span style="color: #6666d0;"&gt;[0003]&lt;/span&gt; "111"
&lt;span style="color: #6666d0;"&gt;[0003]&lt;/span&gt; "222"
&lt;span style="color: #6666d0;"&gt;[4086]&lt;/span&gt; "333

































              "&lt;/pre&gt;
&lt;p&gt;If we step through our demo we can quickly discover that during the last iteration the string variable &lt;code&gt;line&lt;/code&gt; consists of three '&lt;code&gt;3&lt;/code&gt;'-characters followed by 4083 null characters:&lt;/p&gt;
&lt;pre class="brush: cs; gutter: false"&gt; 
    line = "333\0\0\0\0\0 ... \0\0\0";
&lt;/pre&gt;
&lt;p&gt;So what is the reason for this unexpected behaviour and how can we prevent it from happening&lt;/p&gt;
&lt;p&gt;Recall that when you create a view of a memory mapped file, Windows &lt;a href="http://msdn.microsoft.com/en-us/library/aa366761.aspx"&gt;aligns&lt;/a&gt; the view to virtual memory page boundaries. E.g., if your page size is, say, 4096 bytes, a memory-map view can only be 4096, 8192, 12288, ..., &lt;var&gt;N&lt;/var&gt; &amp;times; 4096 bytes large.&lt;/p&gt;
&lt;p&gt;As our data file is smaller than a memory page, we get a view that is as large as a memory page (if the size of virtual memory pages on your machine is not 4096, then the output will also differ accordingly). The memory-map view contains the data supplemented with zeros. When we use a stream reader to read this data, we only reach the EOF mark when we get to the end of the entire view, not to the end of the original data.&lt;/p&gt;
&lt;p&gt;One may wish that the .NET APIs were smart enough to notice the size of the underlying file on disk and to use this information to make sure that the stream reader hits an EOF at the end of the original data. However, this is not always possible, even in principle, for three types of reasons:&lt;/p&gt;
&lt;p&gt;First, it is not always possible to even determine the path of the backing file on disk. The &lt;code&gt;MemoryMappedFile&lt;/code&gt; may have been created not by specifying a physical file, but by &lt;a href="http://msdn.microsoft.com/en-us/library/dd267561.aspx"&gt;referring to a previously memory-mapped file&lt;/a&gt; [&lt;a href="http://msdn.microsoft.com/en-us/library/aa366791.aspx"&gt;OS ref&lt;/a&gt;]. In such case, it is not possible to determine the backing file path. Recall that it is also &lt;a href="http://msdn.microsoft.com/en-us/library/dd267587.aspx"&gt;possible&lt;/a&gt; to create a new &lt;code&gt;MemoryMappedFile&lt;/code&gt; without specifying a backing file on disk at all (by either using the system page file of a temp file) [&lt;a href="http://msdn.microsoft.com/en-us/library/aa366537.aspx"&gt;OS ref&lt;/a&gt;].&lt;/p&gt;
&lt;p&gt;The second reason is that even when the path of the backing disk file is known, it is not in general possible to reliably determine the subset of the memory page that represents actual data versus the subset that is just filling zeros. The memory contents may not directly correspond to the file on disk due to any of the reasons pointed out in the previous section, or simply because the memory has been modified but is not yet flushed.&lt;/p&gt;
&lt;p&gt;Finally, the framework APIs do not have the application-specific domain knowledge about whether consecutive zeros could at all be an intended content of the mapped file or must represent filler bytes to the end of the memory page.&lt;/p&gt;
&lt;h2&gt;Solution: Know your data&lt;/h2&gt;
&lt;p&gt;On the other hand, application logic may very well be able to easily differentiate between useful and junk data.&lt;/p&gt;
&lt;p&gt;For instance, in our particular case we know that the actual data does not contain any null characters, so we could peek ahead and stop reading when we see null characters coming up. Another approach is to define a constant such as&lt;/p&gt;
&lt;pre class="brush: cs; gutter: false"&gt; 
    static readonly char[] FillerChars = new char[] { '\0' };
&lt;/pre&gt;
&lt;p&gt;and then to trim the strings as we read them in:&lt;/p&gt;
&lt;pre class="brush: cs; gutter: false"&gt; 
    String line = rdr.ReadLine().Trim(FillerChars);
&lt;/pre&gt;
&lt;h2&gt;Summary&lt;/h2&gt;
&lt;p&gt;Memory mapped files provide many performance benefits and can be used for inter-process communication as well as for random file access. When using memory mapped files, developers need to be aware of some quirks. One of these quirks is that the size of a memory mapped file view is always blown up to the next virtual memory page boundary. When accessing data from such memory-map views, it is the responsibility of the application developer to use the domain knowledge in order to determine what memory contents represent original data, and what are junk bytes used to fill the space up to the next virtual memory page boundary.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10171770" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/bclteam/archive/tags/System-IO/">System.IO</category><category domain="http://blogs.msdn.com/b/bclteam/archive/tags/memory+mapped+file/">memory mapped file</category><category domain="http://blogs.msdn.com/b/bclteam/archive/tags/stream/">stream</category></item><item><title>Aligning Numbers on the Decimal Separator [Ron Petrusha]</title><link>http://blogs.msdn.com/b/bclteam/archive/2011/05/15/aligning-numbers-on-the-decimal-separator.aspx</link><pubDate>Mon, 16 May 2011 01:34:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10164706</guid><dc:creator>BCL Team</dc:creator><slash:comments>3</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/bclteam/rsscomments.aspx?WeblogPostID=10164706</wfw:commentRss><comments>http://blogs.msdn.com/b/bclteam/archive/2011/05/15/aligning-numbers-on-the-decimal-separator.aspx#comments</comments><description>&lt;p&gt;The composite formatting feature in the .NET Framework makes it easy to left-align or right-align a value in a fixed-width field. If the alignment component of a format item in a composite format string is negative, its corresponding argument is left-aligned. If the alignment component is positive, its corresponding argument is right-aligned. For instance, the following example assigns random numbers to an eleven-element array and displays their values. In the output, the array index is left-aligned in a five-character field, and the array value is right-aligned in a twelve-character field.&lt;/p&gt;
&lt;pre&gt;[Visual Basic]
&lt;span style="color: blue;"&gt;Dim&lt;/span&gt; rnd &lt;span style="color: blue;"&gt;As New&lt;/span&gt; &lt;span style="color: #2b91af;"&gt;Random()&lt;/span&gt;
&lt;span style="color: blue;"&gt;Dim&lt;/span&gt; values(10) &lt;span style="color: blue;"&gt;As Double&lt;/span&gt;
&lt;span style="color: #2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515;"&gt;"{0,-5}{1,12}"&lt;/span&gt;, &lt;span style="color: #a31515;"&gt;"Index"&lt;/span&gt;, &lt;span style="color: #a31515;"&gt;"Value"&lt;/span&gt;)
&lt;span style="color: blue;"&gt;For&lt;/span&gt; ctr &lt;span style="color: blue;"&gt;As Integer&lt;/span&gt; = values.GetLowerBound(0) &lt;span style="color: blue;"&gt;To&lt;/span&gt; values.GetUpperBound(0)
&amp;nbsp;&amp;nbsp;&amp;nbsp; values(ctr) = rnd.NextDouble()
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515;"&gt;" {0,-5} {1,12:F6}"&lt;/span&gt;, ctr, values(ctr))
&lt;span style="color: blue;"&gt;Next&lt;/span&gt;

[C#]
&lt;span style="color: #2b91af;"&gt;Random&lt;/span&gt; rnd = &lt;span style="color: blue;"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af;"&gt;Random&lt;/span&gt;();
&lt;span style="color: blue;"&gt;double&lt;/span&gt;[] values = &lt;span style="color: blue;"&gt;new double&lt;/span&gt;[11];
&lt;span style="color: #2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515;"&gt;"{0,-5}{1,12}"&lt;/span&gt;, &lt;span style="color: #a31515;"&gt;"Index"&lt;/span&gt;, &lt;span style="color: #a31515;"&gt;"Value"&lt;/span&gt;);
&lt;span style="color: blue;"&gt;for&lt;/span&gt; (&lt;span style="color: blue;"&gt;int&lt;/span&gt; ctr = values.GetLowerBound(0); ctr &amp;lt;= values.GetUpperBound(0); ctr++)
{
&amp;nbsp;&amp;nbsp; values[ctr] = rnd.NextDouble();
&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515;"&gt;" {0,-5} {1,12:F6}"&lt;/span&gt;, ctr, values[ctr]);
}
&lt;/pre&gt;
&lt;p&gt;The example produces output similar to the following:&lt;/p&gt;
&lt;pre&gt;&lt;b&gt;Index&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Value&lt;/b&gt;

&amp;nbsp;0&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 0.682236
&amp;nbsp;1&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 0.827866
&amp;nbsp;2&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 0.927542
&amp;nbsp;3&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 0.670535
&amp;nbsp;4&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 0.023612
&amp;nbsp;5&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 0.353050
&amp;nbsp;6&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 0.685052
&amp;nbsp;7&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 0.938842
&amp;nbsp;8&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 0.494007
&amp;nbsp;9&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 0.532631
&amp;nbsp;10&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; 0.978260
&lt;/pre&gt;
&lt;p&gt;The .NET Framework composite formatting feature doesn&amp;rsquo;t support additional forms of alignment such as centering a value or aligning numeric values in a field on their decimal points. However, such forms of alignment can be easily implemented by dynamically building a composite format string or by modifying the string representation of the value to be formatted. This blog post will illustrate both approaches by showing how to align a series of numeric values on their decimal point.&lt;/p&gt;
&lt;p&gt;The first step is to determine the maximum size of the field that is to display the aligned values. In some cases, the field size is static and is known at compile time. In other cases, the precise range of the values to be formatted is based on the format of data that is known only at runtime. However, the alignment component of a format string must consist of a literal numeric value; you cannot supply a variable that represents that value. For example, the composite format string &lt;code&gt;&lt;span style="color: #2b91af;"&gt;"The value is {0,12}."&lt;/span&gt;&lt;/code&gt;&amp;nbsp;indicates that the first argument is to be right-aligned in a twelve-character field. But the composite format string &lt;code&gt;&lt;span style="color: #2b91af;"&gt;"The value is {0,width}."&lt;/span&gt;&lt;/code&gt; throws a &lt;b&gt;FormatException&lt;/b&gt;.&lt;/p&gt;
&lt;p&gt;This means that if we cannot supply a numeric value to the alignment component of a composite format string at design time, we must use string concatenation to dynamically create the format string at runtime. This, in turn, requires an initial pass through the data to be formatted. To align numeric data on a decimal point, we need two items of information: &lt;/p&gt;
&lt;ul type="disc"&gt;
&lt;li&gt;The number of characters in the data item that has the largest number of integral digits.&lt;/li&gt;
&lt;li&gt;The number of characters in the data item that has the largest number of fractional digits.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The sum of these two values, along with the number of characters reserved for the decimal separator, any other formatting styles, and white space, defines the total width of the field. The number of characters in the data item with the largest number of integral digits, along with any formatting styles and leading white space, defines the maximum number of characters that you must accommodate for the value before the decimal separator in the formatted string. For example, to align the values 16.509 and 13052.4 on their decimal point, requires a field width of nine (assuming that we do not want to include any additional styles such as white space or group separators) with a maximum of five integral digits.&lt;/p&gt;
&lt;p&gt;The following example illustrates this first pass through an array of numeric values to determine the total field size and the maximum number of integral characters. Note that the example determines the number of characters in a particular numeric value by calling the &lt;b&gt;ToString&lt;/b&gt; method with a format specifier. &lt;/p&gt;
&lt;pre&gt;[Visual Basic]
&lt;span style="color: blue;"&gt;Dim&lt;/span&gt; numbers() &lt;span style="color: blue;"&gt;As Decimal&lt;/span&gt; = { 3D, 15.4D, 19.008D, 18.62D, 1093.425D }
&lt;span style="color: blue;"&gt;Dim&lt;/span&gt; intDigits, decDigits, decPosition &lt;span style="color: blue;"&gt;As Integer&lt;/span&gt;
&lt;span style="color: blue;"&gt;Dim&lt;/span&gt; decimalSeparator &lt;span style="color: blue;"&gt;As String&lt;/span&gt; = &lt;span style="color: #2b91af;"&gt;NumberFormatInfo&lt;/span&gt;.CurrentInfo.NumberDecimalSeparator
&lt;span style="color: blue;"&gt;For Each&lt;/span&gt; number &lt;span style="color: blue;"&gt;As Decimal In&lt;/span&gt; numbers
&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;Dim&lt;/span&gt; value &lt;span style="color: blue;"&gt;As String&lt;/span&gt; = number.ToString(&lt;span style="color: #a31515;"&gt;"G"&lt;/span&gt;)
&amp;nbsp;&amp;nbsp; decPosition = value.IndexOf(decimalSeparator)
&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;If&lt;/span&gt; intDigits &amp;lt; decPosition &lt;span style="color: blue;"&gt;Then&lt;/span&gt; intDigits = decPosition
&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;If&lt;/span&gt; decDigits &amp;lt; value.Length - (decPosition + 1) &lt;span style="color: blue;"&gt;Then&lt;/span&gt; decDigits = value.Length - (decPosition + 1)
&lt;span style="color: blue;"&gt;Next&lt;/span&gt;

&lt;span style="color: blue;"&gt;Dim&lt;/span&gt; fieldWidth &lt;span style="color: blue;"&gt;As Integer&lt;/span&gt; = intDigits + decimalSeparator.Length + decDigits

&lt;span style="color: #2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515;"&gt;"Maximum number of integral digits: {0}"&lt;/span&gt;, intDigits)
&lt;span style="color: #2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515;"&gt;"Maximum number of decimal digits: {0}"&lt;/span&gt;, decDigits)
&lt;span style="color: #2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515;"&gt;"Total number of characters: {0}"&lt;/span&gt;, fieldWidth)
&lt;span style="color: #2b91af;"&gt;Console&lt;/span&gt;.WriteLine()

[C#]
&lt;span style="color: blue;"&gt;decimal&lt;/span&gt;[] numbers = { 3m, 15.4m, 19.008m, 18.62m, 1093.425m };
&lt;span style="color: blue;"&gt;int&lt;/span&gt; intDigits = 0, decDigits = 0, decPosition = 0;
&lt;span style="color: blue;"&gt;string&lt;/span&gt; decimalSeparator = &lt;span style="color: #2b91af;"&gt;NumberFormatInfo&lt;/span&gt;.CurrentInfo.NumberDecimalSeparator;
&lt;span style="color: blue;"&gt;foreach&lt;/span&gt; (&lt;span style="color: blue;"&gt;decimal&lt;/span&gt; number &lt;span style="color: blue;"&gt;in&lt;/span&gt; numbers)
{
   &lt;span style="color: blue;"&gt;string&lt;/span&gt; value = number.ToString(&lt;span style="color: #a31515;"&gt;"G"&lt;/span&gt;);
&amp;nbsp;&amp;nbsp; decPosition = value.IndexOf(decimalSeparator);
   &lt;span style="color: blue;"&gt;if&lt;/span&gt; (intDigits &amp;lt; decPosition) intDigits = decPosition;
   &lt;span style="color: blue;"&gt;if&lt;/span&gt; (decDigits &amp;lt; value.Length - (decPosition + 1)) decDigits = value.Length - (decPosition + 1);
}

&lt;span style="color: blue;"&gt;int&lt;/span&gt; fieldWidth = intDigits + decimalSeparator.Length + decDigits;

&lt;span style="color: #2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515;"&gt;"Maximum number of integral digits: {0}"&lt;/span&gt;, intDigits);
&lt;span style="color: #2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515;"&gt;"Maximum number of decimal digits: {0}"&lt;/span&gt;, decDigits);
&lt;span style="color: #2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515;"&gt;"Total number of characters: {0}"&lt;/span&gt;, fieldWidth);
&lt;span style="color: #2b91af;"&gt;Console&lt;/span&gt;.WriteLine();
&lt;/pre&gt;
&lt;p&gt;As the output shows, aligning this data on its decimal separator requires that each data item be displayed in an eight-character field, and that each data item be allocated space for four integral characters.&lt;/p&gt;
&lt;pre&gt;Maximum number of integral digits: 4
Maximum number of decimal digits: 3
Total number of characters: 8
&lt;/pre&gt;
&lt;p&gt;Once the first pass through the data determines the total field width and the number of integral characters in each field, a second pass can display the data. To align numeric values on their decimal separator, this second pass must dynamically add the field width to the format string. Since we are aligning the numeric values on their decimal points based on the number of integral characters, the string must define a left-aligned field. When iterating the numeric values in the array, each number must be padded with a sufficient number of leading spaces so that the total length of its integral portion equals the maximum number of integral digits. This allows the numbers to be aligned on their decimal separators.&lt;/p&gt;
&lt;pre&gt;[Visual Basic]
&lt;span style="color: blue;"&gt;Dim&lt;/span&gt; fmt &lt;span style="color: blue;"&gt;As String&lt;/span&gt; = &lt;span style="color: #a31515;"&gt;"Value: {0,-"&lt;/span&gt; + fieldWidth.ToString() + &lt;span style="color: #a31515;"&gt;"}"&lt;/span&gt;
&lt;span style="color: blue;"&gt;For Each&lt;/span&gt; number &lt;span style="color: blue;"&gt;As Decimal In&lt;/span&gt; numbers
&amp;nbsp;&amp;nbsp; decPosition = number.ToString().IndexOf(decimalSeparator)
&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;If&lt;/span&gt; decPosition = -1 &lt;span style="color: blue;"&gt;Then&lt;/span&gt; decPosition = number.ToString().Length

&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;Dim&lt;/span&gt; value &lt;span style="color: blue;"&gt;As String&lt;/span&gt; = &lt;span style="color: blue;"&gt;String&lt;/span&gt;.Format(&lt;span style="color: #a31515;"&gt;"{0}{1}"&lt;/span&gt;, _
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;         &lt;span style="color: blue;"&gt;New String&lt;/span&gt;(&lt;span style="color: #a31515;"&gt;" "c&lt;/span&gt;, intDigits - decPosition), number)

&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af;"&gt;Console&lt;/span&gt;.WriteLine(fmt, value)
&lt;span style="color: blue;"&gt;Next&lt;/span&gt;

[C#]
&lt;span style="color: blue;"&gt;string&lt;/span&gt; fmt = &lt;span style="color: #a31515;"&gt;"Value: {0,-"&lt;/span&gt; + fieldWidth.ToString() + &lt;span style="color: #a31515;"&gt;"}"&lt;/span&gt;;
&lt;span style="font-size: 10.0pt; font-family: 'Courier New'; color: blue;"&gt;foreach&lt;/span&gt; (&lt;span style="color: blue;"&gt;decimal&lt;/span&gt; number &lt;span style="color: blue;"&gt;in&lt;/span&gt; numbers)
{
&amp;nbsp;&amp;nbsp; decPosition = number.ToString().IndexOf(decimalSeparator);
&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;if&lt;/span&gt; (decPosition == -1) decPosition = number.ToString().Length;

&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;string&lt;/span&gt; value = &lt;span style="color: #2b91af;"&gt;String&lt;/span&gt;.Format(&lt;span style="color: #a31515;"&gt;"{0}{1}"&lt;/span&gt;, 
                  &lt;span style="color: blue;"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af;"&gt;String&lt;/span&gt;(&lt;span style="color: #a31515;"&gt;' '&lt;/span&gt;, intDigits - decPosition), number);

&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af;"&gt;Console&lt;/span&gt;.WriteLine(fmt, value);
}
&lt;/pre&gt;
&lt;p&gt;The example displays the following output:&lt;/p&gt;
&lt;pre&gt;Value:&amp;nbsp;&amp;nbsp;&amp;nbsp; 3
Value:&amp;nbsp;&amp;nbsp; 15.4
Value:&amp;nbsp;&amp;nbsp; 19.008
Value:&amp;nbsp;&amp;nbsp; 18.62
Value: 1093.425
&lt;/pre&gt;
&lt;p&gt;Although this example shows how to align numeric values on their decimal point, you can adopt a similar approach to other forms of alignment. To center a numeric value in a field, for example, requires that you know the total field width. Centering the number is then just a matter of determining the length of the string that represents a particular number and padding it with a number of spaces equal to half of the difference between the total field width and the number&amp;rsquo;s length.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10164706" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/bclteam/archive/tags/String/">String</category><category domain="http://blogs.msdn.com/b/bclteam/archive/tags/formatting/">formatting</category></item><item><title>Unexpected effects of the RegEx SET operator [Greg]</title><link>http://blogs.msdn.com/b/bclteam/archive/2011/05/02/unexpected-effects-of-the-regex-set-operator.aspx</link><pubDate>Mon, 02 May 2011 23:24:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10160207</guid><dc:creator>BCL Team</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/bclteam/rsscomments.aspx?WeblogPostID=10160207</wfw:commentRss><comments>http://blogs.msdn.com/b/bclteam/archive/2011/05/02/unexpected-effects-of-the-regex-set-operator.aspx#comments</comments><description>&lt;p&gt;Regular Expressions (RegEx) are a powerful tool for searching for text that matches specific patterns, but it is also a complex tool that requires care and attention to detail. There are many caveats to using RegEx.&lt;br /&gt;Here, I would like to briefly talk about a common caveat when using RegEx: the set operator &lt;code&gt;[ ]&lt;/code&gt; and its effect on the contained tokens...&lt;/p&gt;...(&lt;a href="http://blogs.msdn.com/b/bclteam/archive/2011/05/02/unexpected-effects-of-the-regex-set-operator.aspx"&gt;read more&lt;/a&gt;)&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10160207" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/bclteam/archive/tags/parsing/">parsing</category><category domain="http://blogs.msdn.com/b/bclteam/archive/tags/RegEx/">RegEx</category></item><item><title>Parsing Non-Standard Date and Time Formats [Ron Petrusha]</title><link>http://blogs.msdn.com/b/bclteam/archive/2011/04/13/parsing-non-standard-date-and-time-formats.aspx</link><pubDate>Thu, 14 Apr 2011 00:19:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10153638</guid><dc:creator>BCL Team</dc:creator><slash:comments>3</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/bclteam/rsscomments.aspx?WeblogPostID=10153638</wfw:commentRss><comments>http://blogs.msdn.com/b/bclteam/archive/2011/04/13/parsing-non-standard-date-and-time-formats.aspx#comments</comments><description>&lt;p&gt;Frequently, particularly when dealing with remote data collection devices, an application receives string data containing date and time information that must be converted to either &lt;b&gt;DateTime&lt;/b&gt; or &lt;b&gt;DateTimeOffset&lt;/b&gt; values. In these cases, the most commonly used parsing methods, the overloads of the &lt;b&gt;DateTime.Parse&lt;/b&gt; or &lt;b&gt;DateTimeOffset.Parse&lt;/b&gt; methods, all throw a &lt;b&gt;FormatException&lt;/b&gt; when they attempt to perform the conversion, and their corresponding &lt;b&gt;TryParse&lt;/b&gt; overloads all return &lt;b&gt;false&lt;/b&gt; and assign a data and time of &lt;b&gt;MinValue&lt;/b&gt; to the method&amp;rsquo;s date and time argument. However, the .NET Framework provides two alternative overloaded methods, &lt;b&gt;ParseExact&lt;/b&gt; and &lt;b&gt;TryParseExact&lt;/b&gt;, that can be used to parse the string representations of date and time values.&lt;/p&gt;
&lt;p&gt;In parsing date and time strings, both &lt;b&gt;Parse&lt;/b&gt; and &lt;b&gt;TryParse&lt;/b&gt; use a &lt;b&gt;NumberFormatInfo&lt;/b&gt; object that corresponds either to the current culture or, if one of the overloads with an &lt;b&gt;IFormatProvider&lt;/b&gt; parameter is called, to the culture that corresponds to the &lt;b&gt;IFormatProvider&lt;/b&gt; argument. The properties of this &lt;b&gt;NumberFormatInfo&lt;/b&gt; object determine the acceptable date and time formats that a string can have in order to parse successfully. Even though the number of supported formats is typically sizable, the &lt;b&gt;Parse&lt;/b&gt; and &lt;b&gt;TryParse&lt;/b&gt; methods cannot parse strings in non-standard formats successfully.&lt;/p&gt;
&lt;p&gt;On the other hand, the &lt;b&gt;ParseExact&lt;/b&gt; or &lt;b&gt;TryParseExact&lt;/b&gt; methods are ideal, since they require that a string exactly conform to a particular definable pattern if the parse operation is to succeed. They are useful when either of the following conditions holds true:&lt;/p&gt;
&lt;ul type="disc"&gt;
&lt;li&gt;The precise format of a string containing date and time information is known in advance, as it is when the data is gathered by some data collection object or device.&lt;/li&gt;
&lt;li&gt;User input must have a particular format. &lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The overloads of the &lt;b&gt;ParseExact&lt;/b&gt; and &lt;b&gt;TryParseExact&lt;/b&gt; methods of both the &lt;b&gt;DateTime&lt;/b&gt; and &lt;b&gt;DateTimeOffset&lt;/b&gt; objects allow you to specify either a single pattern or an array of patterns. You to define a pattern by specifying a format string that consists of either a standard format specifier or one or more custom format specifiers. The input string must then conform to that single pattern or to any one of the patterns in the array. Two of the overloads also include a &lt;b&gt;DateTimeStyles&lt;/b&gt; parameter that allows you to define style elements (such as white-space characters) that may be included in the input, or to determine how the input string is to be interpreted (for example, as local or universal time).&lt;/p&gt;
&lt;p&gt;To see how the &lt;b&gt;ParseExact&lt;/b&gt; and &lt;b&gt;TryParseExact&lt;/b&gt; methods can help with parsing date and time strings, let&amp;rsquo;s take three examples. First, in some cases, date and time data is provided to an application as a set of numbers without any separators (for example, &amp;ldquo;20100501061245500&amp;rdquo;). The following code uses a custom date and time format string to do this. &lt;/p&gt;
&lt;pre class="code"&gt;&lt;b&gt;[Visual Basic]&lt;/b&gt;
&lt;span style="color: blue;"&gt;Module&lt;/span&gt; Example
   &lt;span style="color: blue;"&gt;Public Sub&lt;/span&gt; Main()
      &lt;span style="color: blue;"&gt;Dim&lt;/span&gt; fmt &lt;span style="color: blue;"&gt;As String&lt;/span&gt; = &lt;span style="color: #a31515;"&gt;"yyyyMMddhhmmssFFFFFFF"&lt;/span&gt;
      &lt;span style="color: blue;"&gt;Dim&lt;/span&gt; value &lt;span style="color: blue;"&gt;As String&lt;/span&gt; = &lt;span style="color: #a31515;"&gt;"20100501061245500"&lt;/span&gt;
      &lt;span style="color: blue;"&gt;Dim&lt;/span&gt; dt &lt;span style="color: blue;"&gt;As&lt;/span&gt; DateTime = DateTime.ParseExact(value, fmt, &lt;span style="color: blue;"&gt;Nothing&lt;/span&gt;)
      Console.WriteLine(&lt;span style="color: #a31515;"&gt;"{0}--&amp;gt; {1}"&lt;/span&gt;, value, dt)
   &lt;span style="color: blue;"&gt;End Sub&lt;/span&gt;
&lt;span style="color: blue;"&gt;End Module&lt;/span&gt;

&lt;b&gt;[C#]&lt;/b&gt;
&lt;span style="color: blue;"&gt;using&lt;/span&gt; System;

&lt;span style="color: blue;"&gt;public&lt;/span&gt; class&lt;span&gt;&amp;nbsp;&lt;/span&gt; &lt;span style="color: #2b91af;"&gt;Example&lt;/span&gt;
{
   &lt;span style="color: blue;"&gt;public static void&lt;/span&gt; Main()
   {
      &lt;span style="color: blue;"&gt;string&lt;/span&gt; fmt = &lt;span style="color: #a31515;"&gt;"yyyyMMddhhmmssFFFFFFF"&lt;/span&gt;;
      &lt;span style="color: blue;"&gt;string&lt;/span&gt; value = &lt;span style="color: #a31515;"&gt;"20100501061245500"&lt;/span&gt;;
      &lt;span style="color: #2b91af;"&gt;DateTime&lt;/span&gt; dt = &lt;span style="color: #2b91af;"&gt;DateTime&lt;/span&gt;.ParseExact(value, fmt, &lt;span style="color: blue;"&gt;null&lt;/span&gt;);
      &lt;span style="color: #2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515;"&gt;"{0} --&amp;gt; {1}"&lt;/span&gt;, value, dt);
   }
}
&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;The example displays the following output:&lt;/p&gt;
&lt;div&gt;&lt;/div&gt;
&lt;pre&gt;20100501061245500 --&amp;gt; 5/1/2010 6:12:45 AM
&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Second, in some cases, date and time strings include time zone information expressed as the time zone&amp;rsquo;s offset from Coordinated Universal Time (UTC). The z, zz, or zzz custom format specifiers can be used in a custom format string to handle such time zone offsets. For example, the following code uses both the &lt;b&gt;ParseExact&lt;/b&gt; and &lt;b&gt;TryParseExact&lt;/b&gt; methods to parse the string representation of a date and time that contains a time zone offset.&lt;/p&gt;
&lt;div&gt;&lt;/div&gt;
&lt;pre class="code"&gt;&lt;b&gt;[Visual Basic]&lt;/b&gt;
&lt;span style="color: blue;"&gt;Imports System.Globalization&lt;/span&gt;

&lt;span style="color: blue;"&gt;Module&lt;/span&gt; Example&lt;span&gt;&amp;nbsp;&lt;/span&gt;
   &lt;span style="color: blue;"&gt;Sub&lt;/span&gt; Main()&lt;span&gt;&amp;nbsp;&lt;/span&gt;
      &lt;span style="color: blue;"&gt;Dim&lt;/span&gt; value &lt;span style="color: blue;"&gt;As String&lt;/span&gt; = &lt;span style="color: #a31515;"&gt;"12/15/2009 6:32 PM -05:00"&lt;/span&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&lt;span style="color: blue;"&gt;Dim&lt;/span&gt; fmt &lt;span style="color: blue;"&gt;As String&lt;/span&gt; = &lt;span style="color: #a31515;"&gt;"MM/dd/yyyyh:mm tt zzz"&lt;/span&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;Dim&lt;/span&gt; date1 &lt;span style="color: blue;"&gt;As&lt;/span&gt; DateTime&lt;span&gt;&amp;nbsp;&lt;/span&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;If&lt;/span&gt; DateTime.TryParseExact(value, fmt, &lt;span style="color: blue;"&gt;Nothing&lt;/span&gt;, _
                                DateTimeStyles.AllowWhiteSpaces, date1) &lt;span style="color: blue;"&gt;Then&lt;/span&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;    Console.WriteLine(&lt;span style="color: #a31515;"&gt;"Converted '{0}' to {1}, Kind {2}"&lt;/span&gt;, _
                           value, date1, date1.Kind)&lt;span&gt;&amp;nbsp;&lt;/span&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;Else&lt;/span&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;
     &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Console.WriteLine(&lt;span style="color: #a31515;"&gt;"Unable to convert '{0} to a date."&lt;/span&gt;, value)
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;End If&lt;/span&gt;

&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;Try&lt;/span&gt;&lt;span&gt;&amp;nbsp;&lt;/span&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;Dim&lt;/span&gt; date2 &lt;span style="color: blue;"&gt;As&lt;/span&gt; DateTime = DateTime.ParseExact(value, fmt, _
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;            &lt;span style="color: blue;"&gt;Nothing&lt;/span&gt;, DateTimeStyles.AdjustToUniversal)&lt;span&gt;&amp;nbsp;&lt;/span&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Console.WriteLine(&lt;span style="color: #a31515;"&gt;"Converted '{0}' to {1}, Kind {2}"&lt;/span&gt;, _&lt;span&gt;&amp;nbsp;&lt;/span&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;     value, date2, date2.Kind)&lt;span&gt;&amp;nbsp;&lt;/span&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;Catch&lt;/span&gt; e &lt;span style="color: blue;"&gt;As&lt;/span&gt; FormatException&lt;span&gt;&amp;nbsp;&lt;/span&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Console.WriteLine(&lt;span style="color: #a31515;"&gt;"Unable to convert '{0} to a date."&lt;/span&gt;,
                           value)&lt;span&gt;&amp;nbsp;&lt;/span&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;End Try&lt;/span&gt;
&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;End Sub&lt;/span&gt;
&lt;span style="color: blue;"&gt;End Module&lt;/span&gt;

&lt;b&gt;[C#]&lt;/b&gt;
&lt;span style="color: blue;"&gt;using&lt;/span&gt; System;
&lt;span style="color: blue;"&gt;using&lt;/span&gt; System.Globalization;

&lt;span style="color: blue;"&gt;class&lt;/span&gt; &lt;span style="color: #2b91af;"&gt;Example&lt;/span&gt;
{
&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;static void&lt;/span&gt; Main()
&amp;nbsp;&amp;nbsp; {
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;string&lt;/span&gt; value = &lt;span style="color: #a31515;"&gt;@"12/15/2009 6:32 PM -05:00"&lt;/span&gt;;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;string&lt;/span&gt; fmt = &lt;span style="color: #a31515;"&gt;@"MM/dd/yyyy h:mm tt zzz"&lt;/span&gt;;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af;"&gt;DateTime&lt;/span&gt; date1;

&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;if&lt;/span&gt; (&lt;span style="color: #2b91af;"&gt;DateTime&lt;/span&gt;.TryParseExact(value, fmt, &lt;span style="color: blue;"&gt;null&lt;/span&gt;,
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af;"&gt;DateTimeStyles&lt;/span&gt;.AllowWhiteSpaces, &lt;span style="color: blue;"&gt;out&lt;/span&gt; date1))
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515;"&gt;"Converted '{0}' to {1}, Kind {2}"&lt;/span&gt;,
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;value, date1, date1.Kind);
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;else&lt;/span&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515;"&gt;"Unable to convert '{0} to a date."&lt;/span&gt;, value);

&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;try&lt;/span&gt; {
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af;"&gt;DateTime&lt;/span&gt; date2 = &lt;span style="color: #2b91af;"&gt;DateTime&lt;/span&gt;.ParseExact(value, fmt, &lt;span style="color: blue;"&gt;null&lt;/span&gt;,
                          &lt;span style="color: #2b91af;"&gt;DateTimeStyles&lt;/span&gt;.AdjustToUniversal);
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515;"&gt;"Converted '{0}' to {1}, Kind {2}"&lt;/span&gt;,
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;value, date2, date2.Kind); 
      }
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;catch&lt;/span&gt; (&lt;span style="color: #2b91af;"&gt;FormatException&lt;/span&gt;)
      {
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515;"&gt;"Unable to convert '{0} to a date."&lt;/span&gt;, value); 
      } 
&amp;nbsp;&amp;nbsp; }
}
&lt;/pre&gt;
&lt;p&gt;The example displays the following output:&lt;/p&gt;
&lt;div&gt;&lt;/div&gt;
&lt;pre&gt;Converted '12/15/2009 6:32 PM -05:00' to 12/15/2009 3:32:00 PM, Kind Local
Converted '12/15/2009 6:32 PM -05:00' to 12/15/2009 11:32:00 PM, Kind Utc
&lt;/pre&gt;
&lt;p&gt;Note that the parsing method has not only converted a string to a &lt;b&gt;DateTime&lt;/b&gt; value, but that in the process it has also performed a time zone conversion. In the first case, the time was adjusted to the time zone of the computer system on which the application was run (which was U.S. Pacific Standard Time in the case of our example). In the second case, because the &lt;b&gt;ParseExact&lt;/b&gt; method was called with the &lt;i&gt;styles&lt;/i&gt; parameter set to &lt;b&gt;DateTimeStyles.AdjustToUniversal&lt;/b&gt;, the string was converted to Coordinated Universal Time.&lt;/p&gt;
&lt;p&gt;It is possible to avoid the loss of time zone information in the input string by calling the &lt;b&gt;DateTimeOffset.ParseExact&lt;/b&gt; or &lt;b&gt;DateTimeOffset.TryParseExact&lt;/b&gt; method rather than the &lt;b&gt;DateTime.ParseExact&lt;/b&gt; or &lt;b&gt;DateTime.TryParseExact&lt;/b&gt; method, as the following example code shows.&lt;/p&gt;
&lt;pre class="code"&gt;&lt;b&gt;[Visual Basic]&lt;/b&gt;
&lt;span style="color: blue;"&gt;Imports&lt;/span&gt; System.Globalization

&lt;span style="color: blue;"&gt;Module&lt;/span&gt; Example
&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;Public Sub&lt;/span&gt; Main()
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;Dim&lt;/span&gt; value &lt;span style="color: blue;"&gt;As String&lt;/span&gt; = &lt;span style="color: #a31515;"&gt;"12/15/2009 6:32 PM -05:00"&lt;/span&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;Dim&lt;/span&gt; fmt &lt;span style="color: blue;"&gt;As String&lt;/span&gt; = &lt;span style="color: #a31515;"&gt;"MM/dd/yyyy h:mm tt zzz"&lt;/span&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;Dim&lt;/span&gt; date1 &lt;span style="color: blue;"&gt;As&lt;/span&gt; DateTimeOffset

&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;If&lt;/span&gt; DateTimeOffset.TryParseExact(value, fmt, &lt;span style="color: blue;"&gt;Nothing&lt;/span&gt;, _&lt;span&gt;&amp;nbsp;&lt;/span&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;DateTimeStyles.AllowWhiteSpaces, date1) &lt;span style="color: blue;"&gt;Then&lt;/span&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Console.WriteLine(&lt;span style="color: #a31515;"&gt;"Converted '{0}' to {1}"&lt;/span&gt;, value, date1)
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;Else&lt;/span&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Console.WriteLine(&lt;span style="color: #a31515;"&gt;"Unable to convert '{0} to a date."&lt;/span&gt;, value)
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;End If&lt;/span&gt;
&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;End Sub&lt;/span&gt;
&lt;span style="color: blue;"&gt;End Module&lt;/span&gt;

&lt;b&gt;[C#]&lt;/b&gt;
&lt;span style="color: blue;"&gt;using&lt;/span&gt; System;
&lt;span style="color: blue;"&gt;using&lt;/span&gt; System.Globalization;

&lt;span style="color: blue;"&gt;public class&lt;/span&gt; &lt;span style="color: #2b91af;"&gt;Example&lt;/span&gt;
{
&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;public static void&lt;/span&gt; Main()
&amp;nbsp;&amp;nbsp; {
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;string&lt;/span&gt; value = &lt;span style="color: #a31515;"&gt;@"12/15/2009 6:32 PM -05:00"&lt;/span&gt;;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;string&lt;/span&gt; fmt = &lt;span style="color: #a31515;"&gt;@"MM/dd/yyyy h:mm tt zzz"&lt;/span&gt;;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af;"&gt;DateTimeOffset&lt;/span&gt; date1;

&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;if&lt;/span&gt; (&lt;span style="color: #2b91af;"&gt;DateTimeOffset&lt;/span&gt;.TryParseExact(value, fmt, &lt;span style="color: blue;"&gt;null&lt;/span&gt;,
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: #2b91af;"&gt;DateTimeStyles&lt;/span&gt;.AllowWhiteSpaces, &lt;span style="color: blue;"&gt;out&lt;/span&gt; date1))
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515;"&gt;"Converted '{0}' to {1}"&lt;/span&gt;, value, date1);
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;else&lt;/span&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515;"&gt;"Unable to convert '{0} to a date."&lt;/span&gt;, value);
&amp;nbsp;&amp;nbsp; }
}
&lt;/pre&gt;
&lt;p&gt;The example displays the following output:&lt;/p&gt;
&lt;pre&gt;Converted '12/15/2009 6:32 PM -05:00' to 12/15/2009 6:32:00 PM -05:00
&lt;/pre&gt;
&lt;p class="MsoNormal"&gt;As the third and final example, assume that our application must parse a string in the form &amp;ldquo;mm/dd/yy hh:mm:ss PST&amp;rdquo; submitted by a control device. In this case, the time zone is represented by a predefined time zone abbreviation. In this case, the following code successfully parses the string.&lt;/p&gt;
&lt;pre class="code"&gt;&lt;b&gt;[Visual Basic]&lt;/b&gt;
&lt;span style="color: blue;"&gt;Module&lt;/span&gt; Example
&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;Public Sub&lt;/span&gt; Main()
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;Dim&lt;/span&gt; values() &lt;span style="color: blue;"&gt;As String&lt;/span&gt; = {&lt;span style="color: #a31515;"&gt;"12/15/2009 6:32 PM PST"&lt;/span&gt;, _
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #a31515;"&gt;"1/2/2010 4:18 AM PST"&lt;/span&gt;, _
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: #a31515;"&gt;"01/16/2010 11:17 PM PST"&lt;/span&gt;}
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;Dim&lt;/span&gt; fmt &lt;span style="color: blue;"&gt;As String&lt;/span&gt; = &lt;span style="color: #a31515;"&gt;"M/d/yyyy h:mm tt PST"&lt;/span&gt;;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;Dim&lt;/span&gt; dt &lt;span style="color: blue;"&gt;As&lt;/span&gt; DateTime

&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;For Each&lt;/span&gt; value &lt;span style="color: blue;"&gt;As String In&lt;/span&gt; values
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;Try&lt;/span&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; dt = DateTime.ParseExact(value, fmt, &lt;span style="color: blue;"&gt;Nothing&lt;/span&gt;)
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Console.WriteLine(&lt;span style="color: #a31515;"&gt;"'{0}' --&amp;gt; {1}"&lt;/span&gt;, value, dt)
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;Catch&lt;/span&gt; e &lt;span style="color: blue;"&gt;As&lt;/span&gt; FormatException
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Console.WriteLine(&lt;span style="color: #a31515;"&gt;"'{0}': Bad Format"&lt;/span&gt;, value)
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;End Try&lt;/span&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;Next&lt;/span&gt;
&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;End Sub&lt;/span&gt;
&lt;span style="color: blue;"&gt;End Module&lt;/span&gt;

&lt;b&gt;[C#]&lt;/b&gt;
&lt;span style="color: blue;"&gt;using&lt;/span&gt; System;

&lt;span style="color: blue;"&gt;public class&lt;/span&gt; &lt;span style="color: #2b91af;"&gt;Example&lt;/span&gt;
{
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;public static void&lt;/span&gt; Main()
&amp;nbsp;&amp;nbsp;&amp;nbsp; {
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;string&lt;/span&gt;[] values = { &lt;span style="color: #a31515;"&gt;"12/15/2009 6:32 PM PST"&lt;/span&gt;,
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;  &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #a31515;"&gt;"1/2/2010 4:18 AM PST"&lt;/span&gt;,
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;  &amp;nbsp; &lt;span style="color: #a31515;"&gt;"01/16/2010 11:17 PM PST"&lt;/span&gt; };
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;string&lt;/span&gt; fmt = &lt;span style="color: #a31515;"&gt;"M/d/yyyy h:mm tt PST"&lt;/span&gt;;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af;"&gt;DateTime&lt;/span&gt; dt;

&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;foreach&lt;/span&gt; (&lt;span style="color: blue;"&gt;string&lt;/span&gt; value &lt;span style="color: blue;"&gt;in&lt;/span&gt; values)
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;try&lt;/span&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; dt = &lt;span style="color: #2b91af;"&gt;DateTime&lt;/span&gt;.ParseExact(value, fmt, &lt;span style="color: blue;"&gt;null&lt;/span&gt;);
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515;"&gt;"'{0}' --&amp;gt; {1}"&lt;/span&gt;, value, dt);
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }

&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;catch&lt;/span&gt; (&lt;span style="color: #2b91af;"&gt;FormatException&lt;/span&gt;)
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&lt;span style="color: #2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515;"&gt;"'{0}': Bad Format"&lt;/span&gt;, value);
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }
&amp;nbsp;&amp;nbsp;&amp;nbsp; }
}
&lt;/pre&gt;
&lt;div&gt;&lt;/div&gt;
&lt;p&gt;The example displays the following output:&lt;/p&gt;
&lt;div&gt;&lt;/div&gt;
&lt;pre class="code"&gt;'12/15/2009 6:32 PM PST' --&amp;gt; 12/15/2009 6:32:00 PM
'1/2/2010 4:18 AM PST' --&amp;gt; 1/2/2010 4:18:00 AM
'01/16/2010 11:17 PM PST' --&amp;gt; 1/16/2010 11:17:00 PM
&lt;/pre&gt;
&lt;p&gt;In this case, the &lt;b&gt;ParseExact&lt;/b&gt; method recognizes only a single time zone abbreviation at the end of the string. By calling another overload that accepts an array of custom format strings, we can extend the example so that it recognizes multiple time zone abbreviations. The following code uses the &lt;b&gt;DateTimeOffset.TryParseExact&lt;/b&gt; method for this purpose.&lt;/p&gt;
&lt;pre class="code"&gt;&lt;b&gt;[Visual Basic]&lt;/b&gt;
&lt;span style="color: blue;"&gt;Imports&lt;/span&gt; System.Globalization

&lt;span style="color: blue;"&gt;Module&lt;/span&gt; Example
&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;Public Sub&lt;/span&gt; Main()
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;Dim&lt;/span&gt; values() &lt;span style="color: blue;"&gt;As String&lt;/span&gt; = {&lt;span style="color: #a31515;"&gt;"12/15/2009 6:32 PM PST"&lt;/span&gt;, _
&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: #a31515;"&gt;"1/2/2010 4:18 AM PDT"&lt;/span&gt;, _
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #a31515;"&gt;"01/16/2010 11:17 PM CST"&lt;/span&gt;}
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;Dim&lt;/span&gt; fmts() &lt;span style="color: blue;"&gt;As String&lt;/span&gt; = {&lt;span style="color: #a31515;"&gt;"M/d/yyyy h:mm tt PST"&lt;/span&gt;, _
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #a31515;"&gt;"M/d/yyyy h:mm tt PDT"&lt;/span&gt;, _
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: #a31515;"&gt;"M/d/yyyy h:mm tt MST"&lt;/span&gt;, _
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #a31515;"&gt;"M/d/yyyy h:mm tt MDT"&lt;/span&gt;, _
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #a31515;"&gt;"M/d/yyyy h:mm tt CST"&lt;/span&gt;, _
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #a31515;"&gt;"M/d/yyyy h:mm tt CDT"&lt;/span&gt;, _
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span lang="FR" style="color: #a31515;"&gt;"M/d/yyyy h:mm tt EST"&lt;/span&gt;&lt;span lang="FR"&gt;, _&lt;/span&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #a31515;"&gt;"M/d/yyyy h:mm tt EDT"&lt;/span&gt;}
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;Dim&lt;/span&gt; dt &lt;span style="color: blue;"&gt;As&lt;/span&gt; DateTimeOffset

&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;For Each&lt;/span&gt; value &lt;span style="color: blue;"&gt;As String In&lt;/span&gt; values
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;If&lt;/span&gt; DateTimeOffset.TryParseExact(value, fmts, &lt;span style="color: blue;"&gt;Nothing&lt;/span&gt;,
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; DateTimeStyles.None, dt) &lt;span style="color: blue;"&gt;Then&lt;/span&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Console.WriteLine(&lt;span style="color: #a31515;"&gt;"'{0}' --&amp;gt; {1}"&lt;/span&gt;, value, dt)
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;Else&lt;/span&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Console.WriteLine(&lt;span style="color: #a31515;"&gt;"Cannot parse '{0}'"&lt;/span&gt;, value)
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;End If
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Next
&amp;nbsp;&amp;nbsp; End Sub
End Module&lt;/span&gt;

&lt;b&gt;[C#]&lt;/b&gt;
&lt;span style="color: blue;"&gt;using&lt;/span&gt; System;
&lt;span style="color: blue;"&gt;using&lt;/span&gt; System.Globalization;

&lt;span style="color: blue;"&gt;public class&lt;/span&gt; &lt;span style="color: #2b91af;"&gt;Example&lt;/span&gt;
{
&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: blue;"&gt;public&lt;/span&gt; static void&lt;span&gt;&amp;nbsp;&lt;/span&gt; Main()
&amp;nbsp;&amp;nbsp;&amp;nbsp;{
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: blue;"&gt;string&lt;/span&gt;[] values = { &lt;span style="color: #a31515;"&gt;"12/15/2009 6:32 PM PST"&lt;/span&gt;,
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #a31515;"&gt;"1/2/2010 4:18 AM PDT"&lt;/span&gt;,
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #a31515;"&gt;"01/16/2010 11:17 PM CST"&lt;/span&gt; };
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;string&lt;/span&gt;[] fmts = { &lt;span style="color: #a31515;"&gt;"M/d/yyyy h:mm tt PST"&lt;/span&gt;,
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&lt;span style="color: #a31515;"&gt;"M/d/yyyy h:mm tt PDT"&lt;/span&gt;,
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #a31515;"&gt;"M/d/yyyy h:mm tt MST"&lt;/span&gt;,
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #a31515;"&gt;"M/d/yyyy h:mm tt MDT"&lt;/span&gt;,
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #a31515;"&gt;"M/d/yyyy h:mm tt CST"&lt;/span&gt;,
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #a31515;"&gt;"M/d/yyyy h:mm tt CDT"&lt;/span&gt;,
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span lang="FR" style="color: #a31515;"&gt;"M/d/yyyy h:mm tt EST"&lt;/span&gt;&lt;span lang="FR"&gt;,&lt;/span&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #a31515;"&gt;"M/d/yyyy h:mm tt EDT"&lt;/span&gt; };
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af;"&gt;DateTimeOffset&lt;/span&gt; dt;

&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;foreach&lt;/span&gt; (&lt;span style="color: blue;"&gt;string&lt;/span&gt; value &lt;span style="color: blue;"&gt;in&lt;/span&gt; values)
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: blue;"&gt;if&lt;/span&gt; (&lt;span style="color: #2b91af;"&gt;DateTimeOffset&lt;/span&gt;.TryParseExact(value, fmts, &lt;span style="color: blue;"&gt;null&lt;/span&gt;,
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af;"&gt;DateTimeStyles&lt;/span&gt;.None, &lt;span style="color: blue;"&gt;out&lt;/span&gt; dt))
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: #2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515;"&gt;"'{0}' --&amp;gt; {1}"&lt;/span&gt;, value, dt);
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;else&lt;/span&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: #2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515;"&gt;"Cannot parse '{0}'"&lt;/span&gt;, value);
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}
&amp;nbsp;&amp;nbsp;&amp;nbsp;}
}
&lt;/pre&gt;
&lt;p&gt;The example displays the following output:&lt;/p&gt;
&lt;pre&gt;'12/15/2009 6:32 PM PST' --&amp;gt; 12/15/2009 6:32:00 PM -08:00
'1/2/2010 4:18 AM PDT' --&amp;gt; 1/2/2010 4:18:00 AM -08:00
'01/16/2010 11:17 PM CST' --&amp;gt; 1/16/2010 11:17:00 PM -08:00
&lt;/pre&gt;
&lt;div&gt;&lt;/div&gt;
&lt;p&gt;But since we are now parsing times from different time zones, the output reveals a significant limitation of this example: it doesn&amp;rsquo;t recognize the time zone abbreviation in our input strings, and so it assumes that the input string represents the data and time in the local system&amp;rsquo;s time zone (which in this case is in the U.S. Pacific Standard Time zone). We can make our example time zone-aware by using a generic &lt;b&gt;Dictionary&lt;/b&gt; object to look up the time zone identifier from its abbreviation, and supplying the identifier as an argument to the &lt;b&gt;TimeZoneInfo.ConvertTimeBySystemTimeZoneId&lt;/b&gt; method. The following is the revised, time zone-aware version of our example.&lt;/p&gt;
&lt;div&gt;&lt;/div&gt;
&lt;pre class="code"&gt;&lt;b&gt;[Visual Basic]&lt;/b&gt;
&lt;span style="color: blue;"&gt;Imports&lt;/span&gt; System.Collections.Generic
&lt;span style="color: blue;"&gt;Imports&lt;/span&gt; System.Globalization
&lt;span style="color: blue;"&gt;Imports&lt;/span&gt; System.Text.RegularExpressions

&lt;span style="color: blue;"&gt;Module&lt;/span&gt; Example
&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;Public Sub&lt;/span&gt; Main()
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: green;"&gt;' Create dictionary of time zones.&lt;/span&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;Dim&lt;/span&gt; timeZones &lt;span style="color: blue;"&gt;As New&lt;/span&gt; Dictionary(&lt;span style="color: blue;"&gt;Of&lt;/span&gt; &lt;span style="color: blue;"&gt;String&lt;/span&gt;, &lt;span style="color: blue;"&gt;String&lt;/span&gt;)
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; timezones.Add(&lt;span style="color: #a31515;"&gt;"PST"&lt;/span&gt;, &lt;span style="color: #a31515;"&gt;"Pacific Standard Time"&lt;/span&gt;)
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; timezones.Add(&lt;span style="color: #a31515;"&gt;"PDT"&lt;/span&gt;, &lt;span style="color: #a31515;"&gt;"Pacific Standard Time"&lt;/span&gt;)
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; timezones.Add(&lt;span style="color: #a31515;"&gt;"MST"&lt;/span&gt;, &lt;span style="color: #a31515;"&gt;"Mountain Standard Time"&lt;/span&gt;)
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; timezones.Add(&lt;span style="color: #a31515;"&gt;"MDT"&lt;/span&gt;, &lt;span style="color: #a31515;"&gt;"Mountain Standard Time"&lt;/span&gt;)
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; timezones.Add(&lt;span style="color: #a31515;"&gt;"CST"&lt;/span&gt;, &lt;span style="color: #a31515;"&gt;"Central Standard Time"&lt;/span&gt;)
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; timezones.Add(&lt;span style="color: #a31515;"&gt;"CDT"&lt;/span&gt;, &lt;span style="color: #a31515;"&gt;"Central Standard Time"&lt;/span&gt;)
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; timezones.Add(&lt;span style="color: #a31515;"&gt;"EST"&lt;/span&gt;, &lt;span style="color: #a31515;"&gt;"Eastern Standard Time"&lt;/span&gt;)
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; timezones.Add(&lt;span style="color: #a31515;"&gt;"EDT"&lt;/span&gt;, &lt;span style="color: #a31515;"&gt;"Eastern Standard Time"&lt;/span&gt;)

&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;Dim&lt;/span&gt; values() &lt;span style="color: blue;"&gt;As String&lt;/span&gt; = {&lt;span style="color: #a31515;"&gt;"12/15/2009 6:32 PM PST"&lt;/span&gt;, _
&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: #a31515;"&gt;"1/2/2010 4:18 AM PDT"&lt;/span&gt;, _
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: #a31515;"&gt;"01/16/2010 11:17 PM CST"&lt;/span&gt;}

&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;Dim&lt;/span&gt; fmts() &lt;span style="color: blue;"&gt;As String&lt;/span&gt; = {&lt;span style="color: #a31515;"&gt;"M/d/yyyy h:mm tt PST"&lt;/span&gt;, _
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: #a31515;"&gt;"M/d/yyyy h:mm tt PDT"&lt;/span&gt;, _
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;&lt;span style="color: #a31515;"&gt;"M/d/yyyy h:mm tt MST"&lt;/span&gt;, _
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: #a31515;"&gt;"M/d/yyyy h:mm tt MDT"&lt;/span&gt;, _
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: #a31515;"&gt;"M/d/yyyy h:mm tt CST"&lt;/span&gt;, _
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: #a31515;"&gt;"M/d/yyyy h:mm tt CDT"&lt;/span&gt;, _
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: #a31515;"&gt;"M/d/yyyy h:mm tt EST"&lt;/span&gt;, _
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: #a31515;"&gt;"M/d/yyyy h:mm tt EDT"&lt;/span&gt;}

&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;Dim&lt;/span&gt; rgx &lt;span style="color: blue;"&gt;As New&lt;/span&gt; Regex(&lt;span style="color: #a31515;"&gt;"\w(D|S)T"&lt;/span&gt;, RegexOptions.IgnoreCase)
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;Dim&lt;/span&gt; dt &lt;span style="color: blue;"&gt;As&lt;/span&gt; DateTime
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;Dim&lt;/span&gt; tz &lt;span style="color: blue;"&gt;As String&lt;/span&gt; = &lt;span style="color: blue;"&gt;Nothing&lt;/span&gt;

&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;For Each&lt;/span&gt; value &lt;span style="color: blue;"&gt;As String In&lt;/span&gt; values
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;Try&lt;/span&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; tz = rgx.Match(value).Value
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; dt = TimeZoneInfo.ConvertTimeBySystemTimeZoneId( _
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;DateTime.ParseExact(value, fmts, &lt;span style="color: blue;"&gt;Nothing&lt;/span&gt;, DateTimeStyles.None), _
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;timeZones.Item(tz), _
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;nbsp;&amp;nbsp;TimeZoneInfo.Local.Id)
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Console.WriteLine(&lt;span style="color: #a31515;"&gt;"'{0}' --&amp;gt; {1}"&lt;/span&gt;, value, dt)
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;Catch&lt;/span&gt; e &lt;span style="color: blue;"&gt;As&lt;/span&gt; FormatException
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Console.WriteLine(&lt;span style="color: #a31515;"&gt;"Cannot parse '{0}'"&lt;/span&gt;, value)
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;Catch&lt;/span&gt; e &lt;span style="color: blue;"&gt;As&lt;/span&gt; TimeZoneNotFoundException
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Console.WriteLine(&lt;span style="color: #a31515;"&gt;"Cannot identify time zone {0}"&lt;/span&gt;, tz)
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;End Try
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Next
   End Sub
End Module&lt;/span&gt;

&lt;b&gt;[C#]&lt;/b&gt;
&lt;span style="color: blue;"&gt;using&lt;/span&gt; System;
&lt;span style="color: blue;"&gt;using&lt;/span&gt; System.Collections.Generic;
&lt;span style="color: blue;"&gt;using&lt;/span&gt; System.Globalization;
&lt;span style="color: blue;"&gt;using&lt;/span&gt; System.Text.RegularExpressions;

&lt;span style="color: blue;"&gt;public class&lt;/span&gt; &lt;span style="color: #2b91af;"&gt;Example&lt;/span&gt;
{
&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: blue;"&gt;public static void&lt;/span&gt; Main()
&amp;nbsp;&amp;nbsp; {
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: green;"&gt;// Create dictionary of time zones.&lt;/span&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af;"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color: blue;"&gt;string&lt;/span&gt;, &lt;span style="color: blue;"&gt;string&lt;/span&gt;&amp;gt; timeZones = &lt;span style="color: blue;"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af;"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color: blue;"&gt;string&lt;/span&gt;, &lt;span style="color: blue;"&gt;string&lt;/span&gt;&amp;gt;();
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; timeZones.Add(&lt;span style="color: #a31515;"&gt;"PST"&lt;/span&gt;, &lt;span style="color: #a31515;"&gt;"Pacific Standard Time"&lt;/span&gt;);
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; timeZones.Add(&lt;span style="color: #a31515;"&gt;"PDT"&lt;/span&gt;, &lt;span style="color: #a31515;"&gt;"Pacific Standard Time"&lt;/span&gt;);
 &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; timeZones.Add(&lt;span style="color: #a31515;"&gt;"MST"&lt;/span&gt;, &lt;span style="color: #a31515;"&gt;"Mountain Standard Time"&lt;/span&gt;);
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; timeZones.Add(&lt;span style="color: #a31515;"&gt;"MDT"&lt;/span&gt;, &lt;span style="color: #a31515;"&gt;"Mountain Standard Time"&lt;/span&gt;);
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; timeZones.Add(&lt;span style="color: #a31515;"&gt;"CST"&lt;/span&gt;, &lt;span style="color: #a31515;"&gt;"Central Standard Time"&lt;/span&gt;);
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; timeZones.Add(&lt;span style="color: #a31515;"&gt;"CDT"&lt;/span&gt;, &lt;span style="color: #a31515;"&gt;"Central Standard Time"&lt;/span&gt;);
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; timeZones.Add(&lt;span style="color: #a31515;"&gt;"EST"&lt;/span&gt;, &lt;span style="color: #a31515;"&gt;"Eastern Standard Time"&lt;/span&gt;);
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; timeZones.Add(&lt;span style="color: #a31515;"&gt;"EDT"&lt;/span&gt;, &lt;span style="color: #a31515;"&gt;"Eastern Standard Time"&lt;/span&gt;);

&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;string&lt;/span&gt;[] values = { &lt;span style="color: #a31515;"&gt;"12/15/2009 6:32 PM PST"&lt;/span&gt;,
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: #a31515;"&gt;"1/2/2010 4:18 AM PDT"&lt;/span&gt;,
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: #a31515;"&gt;"01/16/2010 11:17 PM CST"&lt;/span&gt; };

&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;string&lt;/span&gt;[] fmts = { &lt;span style="color: #a31515;"&gt;"M/d/yyyy h:mm tt PST"&lt;/span&gt;,
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #a31515;"&gt;"M/d/yyyy h:mm tt PDT"&lt;/span&gt;,
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #a31515;"&gt;"M/d/yyyy h:mm tt MST"&lt;/span&gt;,
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #a31515;"&gt;"M/d/yyyy h:mm tt MDT"&lt;/span&gt;,
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #a31515;"&gt;"M/d/yyyy h:mm tt CST"&lt;/span&gt;,
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #a31515;"&gt;"M/d/yyyy h:mm tt CDT"&lt;/span&gt;,
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #a31515;"&gt;"M/d/yyyy h:mm tt EST"&lt;/span&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #a31515;"&gt;"M/d/yyyy h:mm tt EDT"&lt;/span&gt; };

&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: #2b91af;"&gt;Regex&lt;/span&gt; rgx = &lt;span style="color: blue;"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af;"&gt;Regex&lt;/span&gt;(&lt;span style="color: #a31515;"&gt;@"\w(D|S)T"&lt;/span&gt;, &lt;span style="color: #2b91af;"&gt;RegexOptions&lt;/span&gt;.IgnoreCase);
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af;"&gt;DateTime&lt;/span&gt; dt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;string&lt;/span&gt; tz = &lt;span style="color: blue;"&gt;null&lt;/span&gt;;

&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue;"&gt;foreach&lt;/span&gt; (&lt;span style="color: blue;"&gt;string&lt;/span&gt; value &lt;span style="color: blue;"&gt;in&lt;/span&gt; values)
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: blue;"&gt;try&lt;/span&gt; {
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;tz = rgx.Match(value).Value;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; dt = &lt;span style="color: #2b91af;"&gt;TimeZoneInfo&lt;/span&gt;.ConvertTimeBySystemTimeZoneId(
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: #2b91af;"&gt;DateTime&lt;/span&gt;.ParseExact(value, fmts, &lt;span style="color: blue;"&gt;null&lt;/span&gt;, &lt;span style="color: #2b91af;"&gt;DateTimeStyles&lt;/span&gt;.None),
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;timeZones[tz], &lt;span style="color: #2b91af;"&gt;TimeZoneInfo&lt;/span&gt;.Local.Id);
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515;"&gt;"'{0}'--&amp;gt; {1}"&lt;/span&gt;, value, dt);
&amp;nbsp;&amp;nbsp;&amp;nbsp;   &amp;nbsp;&amp;nbsp; }
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;   &lt;span style="color: blue;"&gt;catch&lt;/span&gt; (&lt;span style="color: #2b91af;"&gt;FormatException&lt;/span&gt;) {
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;   &lt;span style="color: #2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515;"&gt;"Cannot parse '{0}'"&lt;/span&gt;, value);
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;    }
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;    &lt;span style="color: blue;"&gt;catch&lt;/span&gt; (&lt;span style="color: #2b91af;"&gt;TimeZoneNotFoundException&lt;/span&gt;) {
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;   &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: #2b91af;"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color: #a31515;"&gt;"Cannot identify time zone {0}"&lt;/span&gt;, tz);
 &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;    }
&amp;nbsp;&amp;nbsp;    }
   }
}
&lt;/pre&gt;
&lt;p&gt;The example displays the following output:&lt;/p&gt;
&lt;pre&gt;'12/15/2009 6:32 PM PST' --&amp;gt; 12/15/2009 6:32:00 PM
'1/2/2010 4:18 AM PDT' --&amp;gt; 1/2/2010 4:18:00 AM
'01/16/2010 11:17 PM CST' --&amp;gt; 1/16/2010 9:17:00 PM
&lt;/pre&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10153638" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/bclteam/archive/tags/parsing/">parsing</category><category domain="http://blogs.msdn.com/b/bclteam/archive/tags/Globalization/">Globalization</category><category domain="http://blogs.msdn.com/b/bclteam/archive/tags/Time+and+Calendar/">Time and Calendar</category></item><item><title>Hardening Server Applications [Immo]</title><link>http://blogs.msdn.com/b/bclteam/archive/2011/04/01/hardening-server-applications.aspx</link><pubDate>Fri, 01 Apr 2011 07:04:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10148601</guid><dc:creator>BCL Team</dc:creator><slash:comments>12</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/bclteam/rsscomments.aspx?WeblogPostID=10148601</wfw:commentRss><comments>http://blogs.msdn.com/b/bclteam/archive/2011/04/01/hardening-server-applications.aspx#comments</comments><description>&lt;p&gt;From time to time a company ships a product that has a huge impact on their ecosystem. A good example for us is certainly .NET. The biggest value proposition that managed code has is that it is, well, managed code. The CLR provides runtime management components such as a garbage collector or reflection that are aimed at reducing the likelihood of bugs and at increasing the developer's productivity. These features allow developers to focus on building their applications instead of tweaking and massaging mechanics. After all, the hope is that by improving the software that is used for developing other software we improve software on a broader scale (how meta!).&lt;/p&gt;
&lt;p&gt;Today we are proud to make an announcement that potentially marks a milestone similar to the &lt;a href="http://www.microsoftpdc.com/PDCClassics/PDC2000"&gt;PDC 2000&lt;/a&gt; announcement of .NET. Several teams at Microsoft worked during the last years on an upcoming product &amp;ndash; code named "Source Code".&lt;/p&gt;
&lt;h2&gt;The Problem &lt;/h2&gt;
&lt;p&gt;We all have seen it: a customer reports a bug and after debugging it for a while we realize that the bug fix involves changing a single line. Sometimes, the fix only involves fixing a single character, such as the famous &lt;a href="http://en.wikipedia.org/wiki/Off_by_one_error"&gt;off-by-one error&lt;/a&gt; where one only needs to replace "&amp;lt;=" by "&amp;lt;".&lt;/p&gt;
&lt;p&gt;Quite frequently, small errors can have devastating effects. For example, an &lt;a href="http://en.wikipedia.org/wiki/Ariane_5_Flight_501"&gt;Ariane 5&lt;/a&gt; launch vehicle had to self-destruct due to a single casting error where a 64 bit floating point value was converted to a 16 bit integer. This caused the flight computer to make wrong adjustments due an arithmetic overflow.&lt;/p&gt;
&lt;h2&gt;How "Source Code" works&lt;/h2&gt;
&lt;p&gt;Research has investigated several strategies to enable computers to learn. One fruitful approach is &lt;a href="http://en.wikipedia.org/wiki/Genetic_programming"&gt;genetic programming&lt;/a&gt;.&lt;/p&gt;
&lt;blockquote style="font-style: italic;"&gt;
&lt;p&gt;In artificial intelligence, Genetic Programming is an evolutionary algorithm-based methodology inspired by biological evolution to find computer programs that perform a user-defined task.&lt;/p&gt;
&lt;p style="text-align: right;"&gt;---Wikipedia &lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;The basic idea is that by mutating existing code and applying a selection-function one can automatically find a computer program that solves a given problem.&lt;/p&gt;
&lt;p&gt;During the last years the BCL team, the wider &lt;a href="http://blogs.msdn.com/b/clrteam/"&gt;CLR team&lt;/a&gt; and Visual Studio worked together with Microsoft Research to build a product around this idea. The result, code named "Source Code", is a combination of new technologies with evolved versions of existing technologies such as &lt;a href="http://msdn.microsoft.com/en-us/library/dd264915.aspx"&gt;IntelliTrace&lt;/a&gt;, &lt;a href="http://en.wikipedia.org/wiki/Software_transactional_memory"&gt;software transactional memory&lt;/a&gt; (STM) and &lt;a href="http://research.microsoft.com/en-us/projects/pex/"&gt;Pex&lt;/a&gt;. The basic idea is simple. Whenever the CLR discovers an unhandled exception it rolls back the state of the applicationto a point in time prior to the crash (the default is 8 minutes but can be configured). To do this, the CLR uses a full IntelliTrace recording so that the whole runtime state, including the heap, can be properly restored. Then, the stack trace of the unhandled exception is analyzed to detect which method is the most likely culprit. This information is passed to Pex in order to create a permutated version of the method body ("mutation"). This enables new code paths not previously explored in the application. After that, the CLR resumes execution. If the application crashes again, it repeats the above process until a code path is found that avoids the error ("selection"). Over time, successful code changes persist improving the overall fitness of the application ("survival of the fittest").&lt;/p&gt;
&lt;div style="text-align: center;"&gt;&lt;img src="http://blogs.msdn.com/cfs-filesystemfile.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-30-50-images/5270.StarTrek_2D00_TheUltimateComputer_2D00_M5.jpg" alt="M5 Multitronic System from the Star Trek episode 'The Ultimate Computer'" title="M5 Multitronic System from the Star Trek episode 'The Ultimate Computer'" style="margin-bottom:10px; border:2px solid #9999BB" /&gt;
&lt;p&gt;Picture of the M5 computer in the &lt;a href="http://en.wikipedia.org/wiki/The_Ultimate_Computer"&gt;Star Trek episode "The Ultimate Computer".&lt;/a&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;As a result of the above process as application will automatically correct itself over time! The brilliant Dr. Richard Daystrom, the designer of the "M5 Multitronic System" (pictured above) would be very pleased to see this advancement.&lt;/p&gt;
&lt;p&gt;Currently the technology is in an early prototype state and we are working on removing some restrictions:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Because of the involved downtimes during rollback and mutation, this scenario will only be available to &lt;a href="http://www.microsoft.com/windowsazure/getstarted/"&gt;Windows Azure&lt;/a&gt; based ASP.NET applications. For the future, we plan to extend the support to client applications as well.&lt;/li&gt;
&lt;li&gt;"Source Code" will only save a limited number of applications. We have seen cases where partially working applications are displaced from the cache by more buggy applications. Our next goal is to improve the cache policy to avoid these situations.&lt;/li&gt;
&lt;li&gt;The early CTP does not include support for management and monitoring but we are actively working to get "Source Code" integrated with the &lt;a href="http://www.microsoft.com/systemcenter/en/us/products.aspx"&gt;Microsoft System Center products&lt;/a&gt;.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;You can download a CTP &lt;a href="http://en.wikipedia.org/wiki/Source_Code_%28film%29"&gt;here&lt;/a&gt;.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10148601" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/bclteam/archive/tags/managed/">managed</category><category domain="http://blogs.msdn.com/b/bclteam/archive/tags/News/">News</category></item><item><title>Optimizing Regex Performance, Part 3 [Ron Petrusha]</title><link>http://blogs.msdn.com/b/bclteam/archive/2011/03/28/optimizing-regex-performance-part-3-ron-petrusha.aspx</link><pubDate>Tue, 29 Mar 2011 04:55:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10146961</guid><dc:creator>BCL Team</dc:creator><slash:comments>2</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/bclteam/rsscomments.aspx?WeblogPostID=10146961</wfw:commentRss><comments>http://blogs.msdn.com/b/bclteam/archive/2011/03/28/optimizing-regex-performance-part-3-ron-petrusha.aspx#comments</comments><description>&lt;p&gt;Regular expressions in the .NET Framework support a number of grouping constructs, which allow a regular expression pattern to be grouped into one or more subexpressions. Grouping constructs are essential for creating backreferences, as well as for defining a subexpression to which a quantifier is applied. &lt;/p&gt;
&lt;h2&gt;The Performance Impact of Capturing Groups&lt;/h2&gt;
&lt;p&gt;The most commonly used grouping constructs in the .NET Framework regular expression language are &lt;b&gt;(&lt;i&gt;subexpression&lt;/i&gt;)&lt;/b&gt;, which defines a numbered capturing group, and &lt;b&gt;(?&amp;lt;&lt;i&gt;name&lt;/i&gt;&amp;gt; &lt;i&gt;subexpression&lt;/i&gt;)&lt;/b&gt;, which defines a named capturing group. The use of these language elements, however, has a definite cost; they cause the &lt;b&gt;GroupCollection&lt;/b&gt; object returned by the &lt;b&gt;Match.Groups&lt;/b&gt; property to be populated with the most recent unnamed or named captures, and if a single grouping construct has captured multiple substrings in the input string, they also populate the &lt;b&gt;CaptureCollection&lt;/b&gt; object returned by the &lt;b&gt;Group.Captures&lt;/b&gt; property of a particular capturing group with multiple &lt;b&gt;Capture&lt;/b&gt; objects.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;For example, the regular expression &lt;code&gt;(\b(\w+)[;,]?\s?)+([.?!])&lt;/code&gt; is designed to capture an entire sentence, and the subexpression &lt;code&gt;(\w+)&lt;/code&gt; is designed to capture the individual words in that sentence. (See &lt;a href="http://msdn.microsoft.com/en-us/library/az24scfc.aspx"&gt;Regular Expression Language Elements&lt;/a&gt; for reference documentation for the regular expression language supported by the .NET Framework.) The regular expression defines three capturing groups, which are listed in the following table. In addition, the first group in the &lt;b&gt;GroupCollection&lt;/b&gt; object (at index 0) contains the complete pattern match; the values of its &lt;b&gt;Group.Index&lt;/b&gt;, &lt;b&gt;Group.Length&lt;/b&gt;, &lt;b&gt;Group.Success&lt;/b&gt;, and &lt;b&gt;Group.Value&lt;/b&gt; properties are identical to the values of its parent &lt;b&gt;Match&lt;/b&gt; object. &lt;/p&gt;
&lt;div&gt;&lt;/div&gt;
&lt;table cellpadding="0" cellspacing="0" border="1" style="margin-left:.75pt;border-collapse:collapse;border:none"&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td width="90" valign="top" style="padding-bottom: 0in; padding-left: 5.4pt; width: 67.65pt; padding-right: 5.4pt; padding-top: 0in; border: windowtext 1pt solid;"&gt;&lt;b&gt;Index&lt;/b&gt; &lt;/td&gt;
&lt;td width="168" valign="top" style="border-bottom: windowtext 1pt solid; border-left: medium none; padding-bottom: 0in; padding-left: 5.4pt; width: 1.75in; padding-right: 5.4pt; border-top: windowtext 1pt solid; border-right: windowtext 1pt solid; padding-top: 0in;"&gt;&lt;b&gt;Pattern&lt;/b&gt; &lt;/td&gt;
&lt;td width="379" valign="top" style="border-bottom: windowtext 1pt solid; border-left: medium none; padding-bottom: 0in; padding-left: 5.4pt; width: 3.95in; padding-right: 5.4pt; border-top: windowtext 1pt solid; border-right: windowtext 1pt solid; padding-top: 0in;"&gt;&lt;b&gt;Description&lt;/b&gt;
&lt;div&gt;&lt;/div&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td width="90" valign="top" style="border-bottom: windowtext 1pt solid; border-left: windowtext 1pt solid; padding-bottom: 0in; padding-left: 5.4pt; width: 67.65pt; padding-right: 5.4pt; border-top: medium none; border-right: windowtext 1pt solid; padding-top: 0in;"&gt;1 &lt;/td&gt;
&lt;td width="168" valign="top" style="border-bottom: windowtext 1pt solid; border-left: medium none; padding-bottom: 0in; padding-left: 5.4pt; width: 1.75in; padding-right: 5.4pt; border-top: medium none; border-right: windowtext 1pt solid; padding-top: 0in;"&gt;&lt;code&gt;(\b(\w+)[;,]?\s?)&lt;/code&gt; &lt;/td&gt;
&lt;td width="379" valign="top" style="border-bottom: windowtext 1pt solid; border-left: medium none; padding-bottom: 0in; padding-left: 5.4pt; width: 3.95in; padding-right: 5.4pt; border-top: medium none; border-right: windowtext 1pt solid; padding-top: 0in;"&gt;Captures a word in the sentence, along with any following punctuation mark and trailing space. The &lt;b&gt;+&lt;/b&gt; quantifier is applied to the group so that the regular expression engine will advance beyond the first word in the input string to capture all words in the sentence.
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td width="90" valign="top" style="border-bottom: windowtext 1pt solid; border-left: windowtext 1pt solid; padding-bottom: 0in; padding-left: 5.4pt; width: 67.65pt; padding-right: 5.4pt; border-top: medium none; border-right: windowtext 1pt solid; padding-top: 0in;"&gt;2
&lt;div&gt;&lt;/div&gt;
&lt;/td&gt;
&lt;td width="168" valign="top" style="border-bottom: windowtext 1pt solid; border-left: medium none; padding-bottom: 0in; padding-left: 5.4pt; width: 1.75in; padding-right: 5.4pt; border-top: medium none; border-right: windowtext 1pt solid; padding-top: 0in;"&gt;&lt;code&gt;(\w+)&lt;/code&gt; &lt;/td&gt;
&lt;td width="379" valign="top" style="border-bottom: windowtext 1pt solid; border-left: medium none; padding-bottom: 0in; padding-left: 5.4pt; width: 3.95in; padding-right: 5.4pt; border-top: medium none; border-right: windowtext 1pt solid; padding-top: 0in;"&gt;Captures a word in the sentence
&lt;div&gt;&lt;/div&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td width="90" valign="top" style="border-bottom: windowtext 1pt solid; border-left: windowtext 1pt solid; padding-bottom: 0in; padding-left: 5.4pt; width: 67.65pt; padding-right: 5.4pt; border-top: medium none; border-right: windowtext 1pt solid; padding-top: 0in;"&gt;3 &lt;/td&gt;
&lt;td width="168" valign="top" style="border-bottom: windowtext 1pt solid; border-left: medium none; padding-bottom: 0in; padding-left: 5.4pt; width: 1.75in; padding-right: 5.4pt; border-top: medium none; border-right: windowtext 1pt solid; padding-top: 0in;"&gt;&lt;code&gt;([.?!])&lt;/code&gt; &lt;/td&gt;
&lt;td width="379" valign="top" style="border-bottom: windowtext 1pt solid; border-left: medium none; padding-bottom: 0in; padding-left: 5.4pt; width: 3.95in; padding-right: 5.4pt; border-top: medium none; border-right: windowtext 1pt solid; padding-top: 0in;"&gt;Captures the punctuation mark used to end the sentence.
&lt;div&gt;&lt;/div&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;The following example uses this regular expression to extract a sentence, its individual words, and its ending punctuation mark from an input string.&lt;/p&gt;
&lt;div&gt;&lt;/div&gt;
&lt;pre&gt;[Visual Basic]
&lt;span style="color:blue"&gt;Imports&lt;/span&gt; System.Text.RegularExpressions

&lt;span style="color:blue"&gt;Module&lt;/span&gt; &lt;span style="color:#2B91AF"&gt;Example&lt;/span&gt;
   &lt;span style="color:blue"&gt;Public Sub&lt;/span&gt; Main()
      &lt;span style="color:blue"&gt;Dim&lt;/span&gt; pattern &lt;span style="color:blue"&gt;As String&lt;/span&gt; = &lt;span style="color:#A31515"&gt;"(\b(\w+)[;,]?\s?)+([.?!])"&lt;/span&gt;

      &lt;span style="color:blue"&gt;Dim&lt;/span&gt; input &lt;span style="color:blue"&gt;As String&lt;/span&gt; = &lt;span style="color:#A31515"&gt;"This is a short, silly sentence."&lt;/span&gt;

      &lt;span style="color:blue"&gt;Dim&lt;/span&gt; match &lt;span style="color:blue"&gt;As&lt;/span&gt; &lt;span style="color:#2B91AF"&gt;Match&lt;/span&gt; = &lt;span style="color:#2B91AF"&gt;Regex&lt;/span&gt;.Match(input, pattern)
      &lt;span style="color:blue"&gt;If&lt;/span&gt; match.Success &lt;span style="color:blue"&gt;Then&lt;/span&gt;

         &lt;span style="color:#2B91AF"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#A31515"&gt;"'{0}' found at position {1}"&lt;/span&gt;,
                           match.Value, match.Index)

         &lt;span style="color:blue"&gt;If&lt;/span&gt; match.Groups.Count &amp;gt; 1 &lt;span style="color:blue"&gt;Then&lt;/span&gt;
            &lt;span style="color:blue"&gt;For&lt;/span&gt; ctr &lt;span style="color:blue"&gt;As Integer&lt;/span&gt; = 1 &lt;span style="color:blue"&gt;To&lt;/span&gt; match.Groups.Count - 1
               &lt;span style="color:blue"&gt;Dim&lt;/span&gt; grp &lt;span style="color:blue"&gt;As&lt;/span&gt; &lt;span style="color:#2B91AF"&gt;Group&lt;/span&gt; = match.Groups(ctr)
               &lt;span style="color:#2B91AF"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#A31515"&gt;"   Group {0}: '{1}'"&lt;/span&gt;,
                                 ctr, grp) 

               &lt;span style="color:blue"&gt;For&lt;/span&gt; cctr &lt;span style="color:blue"&gt;As Integer&lt;/span&gt; = 0 To grp.Captures.Count - 1
                  &lt;span style="color:#2B91AF"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#A31515"&gt;"Capture {0}: '{1}'"&lt;/span&gt;,
                                    cctr, grp.Captures(cctr).Value)
               &lt;span style="color:blue"&gt;Next
            Next
         End If
      End If
   End Sub
End Module&lt;/span&gt;

[C#]
&lt;span style="color:blue"&gt;using&lt;/span&gt; System;
&lt;span style="color:blue"&gt;using&lt;/span&gt; System.Text.RegularExpressions;

&lt;span style="color:blue"&gt;public class&lt;/span&gt; &lt;span style="color:#2B91AF"&gt;Example&lt;/span&gt;
{
   &lt;span style="color:blue"&gt;public static void&lt;/span&gt; Main()
   {
      &lt;span style="color:blue"&gt;string&lt;/span&gt; pattern = @&lt;span style="color:#A31515"&gt;"(\b(\w+)[;,]?\s?)+([.?!])"&lt;/span&gt;;
      &lt;span style="color:blue"&gt;string&lt;/span&gt; input = &lt;span style="color:#A31515"&gt;"This is a short, silly sentence."&lt;/span&gt;;

      &lt;span style="color:#2B91AF"&gt;Match&lt;/span&gt; match = &lt;span style="color:#2B91AF"&gt;Regex&lt;/span&gt;.Match(input, pattern);
      &lt;span style="color:blue"&gt;if&lt;/span&gt; (match.Success) {
         &lt;span style="color:#2B91AF"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#A31515"&gt;"'{0}' found at position {1}"&lt;/span&gt;,
                           match.Value, match.Index);
         &lt;span style="color:blue"&gt;if&lt;/span&gt; (match.Groups.Count &amp;gt; 1)
            &lt;span style="color:blue"&gt;for&lt;/span&gt; (&lt;span style="color:blue"&gt;int&lt;/span&gt; ctr = 1; ctr &amp;lt;= match.Groups.Count - 1; ctr++) {
               &lt;span style="color:#2B91AF"&gt;Group&lt;/span&gt; grp = match.Groups[ctr];
               &lt;span style="color:#2B91AF"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#A31515"&gt;"   Group {0}: '{1}'"&lt;/span&gt;, ctr, grp);  
               &lt;span style="color:blue"&gt;for&lt;/span&gt; (&lt;span style="color:blue"&gt;int&lt;/span&gt; cctr = 0; cctr &amp;lt;= grp.Captures.Count - 1; cctr++)
                  &lt;span style="color:#2B91AF"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#A31515"&gt;"     Capture {0}: '{1}'"&lt;/span&gt;, 
                                    cctr, grp.Captures[cctr].Value);
            }
      }
   }
}

&lt;/pre&gt;
&lt;div&gt;&lt;/div&gt;
&lt;p&gt;The example displays the following output. Note that the &lt;b&gt;CaptureCollection&lt;/b&gt; captured by the first group captures each word in the sentence along with a following punctuation character if it does not conclude the sentence, the &lt;b&gt;CaptureCollection&lt;/b&gt; captured by the second group contains each word in the sentence, and the final group contains only the sentence&amp;rsquo;s final punctuation mark.&lt;/p&gt;
&lt;div&gt;&lt;/div&gt;
&lt;pre&gt;'This is a short, silly sentence.' found at position 0
   Group 1: 'sentence'
      Capture 0: 'This '
      Capture 1: 'is '
      Capture 2: 'a '
      Capture 3: 'short, '
      Capture 4: 'silly '
      Capture 5: 'sentence'
   Group 2: 'sentence'
      Capture 0: 'This'
      Capture 1: 'is'
      Capture 2: 'a'
      Capture 3: 'short'
      Capture 4: 'silly'
      Capture 5: 'sentence'
   Group 3: '.'
      Capture 0: '.'
&lt;/pre&gt;
&lt;div&gt;&lt;/div&gt;
&lt;p&gt;In this regular expression, our first capturing group is present only so that a quantifier can be applied to it. This allows the regular expression engine to advance from one word to the next, and so to capture an entire sentence. The second group is useful if we want to programmatically capture the individual words from the sentence, which are available from the &lt;b&gt;CaptureCollection&lt;/b&gt; object. The third is useful if we want to determine which punctuation symbol ended the sentence; it is available from the &lt;b&gt;GroupCollection&lt;/b&gt; object. &lt;/p&gt;
&lt;div&gt;&lt;/div&gt;
&lt;p&gt;We can disable captures (so that the &lt;b&gt;GroupCollection&lt;/b&gt; and &lt;b&gt;CaptureCollection&lt;/b&gt; objects are not populated as matches are found) by using the &lt;code&gt;(?:&lt;i&gt;subexpression&lt;/i&gt;)&lt;/code&gt; language element. We can assess the impact that capturing groups have on performance by using a &lt;b&gt;StopWatch&lt;/b&gt; object to measure the execution time of the following three similar regular expressions when we use each to extract all of the sentences in the text of Theodore Dreiser's &lt;i&gt;The Financier&lt;/i&gt;:&lt;/p&gt;
&lt;div&gt;&lt;/div&gt;
&lt;ul type="disc"&gt;
&lt;li&gt;The original regular expression, &lt;code&gt;(\b(\w+)[;,]?\s?)+([.?!])&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;A regular expression that disables captures by the first group, &lt;code&gt;(?:\b(\w+)[;,]?\s?)+([.?!])&lt;/code&gt;. This group exists only so that a quantifier could be applied to it.&lt;/li&gt;
&lt;li&gt;A regular expression that has no capturing groups, &lt;code&gt;(?:\b(?:\w+)[;,]?\s?)+[.?!]&lt;/code&gt;. It captures the entire sentence only, and disables all capturing groups. (It actually returns a &lt;b&gt;Match&lt;/b&gt; object whose &lt;b&gt;Groups&lt;/b&gt; property returns a &lt;b&gt;GroupCollection&lt;/b&gt; object with a single &lt;b&gt;Group&lt;/b&gt; object. This group at index 0 represents the entire match; it is always present and cannot be suppressed.&lt;/li&gt;
&lt;/ul&gt;
&lt;div&gt;&lt;/div&gt;
&lt;p&gt;The source code for the example is:&lt;/p&gt;
&lt;div&gt;&lt;/div&gt;
&lt;pre&gt;[Visual Basic]
&lt;span style="color:blue"&gt;Imports&lt;/span&gt; System.Diagnostics
&lt;span style="color:blue"&gt;Imports&lt;/span&gt; System.IO

&lt;span style="color:blue"&gt;Imports&lt;/span&gt; System.Text.RegularExpressions

&lt;span style="color:blue"&gt;Module&lt;/span&gt; &lt;span style="color:#2B91AF"&gt;Example&lt;/span&gt;
   &lt;span style="color:blue"&gt;Public Sub&lt;/span&gt; Main()
      &lt;span style="color:blue"&gt;Dim&lt;/span&gt; patterns() &lt;span style="color:blue"&gt;As String&lt;/span&gt; = { &lt;span style="color:#A31515"&gt;"(\b(\w+)[;,]?\s?)+([.?!])"&lt;/span&gt;, 
                                   &lt;span style="color:#A31515"&gt;"(?:\b(\w+)[;,]?\s?)+([.?!])"&lt;/span&gt;,
                                   &lt;span style="color:#A31515"&gt;"(?:\b(?:\w+)[;,]?\s?)+[.?!]"&lt;/span&gt; }
      &lt;span style="color:blue"&gt;Dim&lt;/span&gt; input &lt;span style="color:blue"&gt;As String&lt;/span&gt; = (&lt;span style="color:blue"&gt;New&lt;/span&gt; &lt;span style="color:#2B91AF"&gt;StreamReader&lt;/span&gt;(&lt;span style="color:#A31515"&gt;".\Dreiser_TheFinancier.txt"&lt;/span&gt;)).ReadToEnd()
      &lt;span style="color:blue"&gt;Dim&lt;/span&gt; sw &lt;span style="color:blue"&gt;As&lt;/span&gt; &lt;span style="color:#2B91AF"&gt;Stopwatch&lt;/span&gt;

      &lt;span style="color:blue"&gt;For Each&lt;/span&gt; pattern &lt;span style="color:blue"&gt;In&lt;/span&gt; patterns
         &lt;span style="color:green"&gt;' Instantiate the regular expression object before measuring performance.&lt;/span&gt;
         &lt;span style="color:blue"&gt;Dim&lt;/span&gt; regex &lt;span style="color:blue"&gt;As New&lt;/span&gt; &lt;span style="color:#2B91AF"&gt;Regex&lt;/span&gt;(pattern)

         &lt;span style="color:green"&gt;' Time matches.&lt;/span&gt;

         sw = &lt;span style="color:#2B91AF"&gt;Stopwatch&lt;/span&gt;.StartNew()

         &lt;span style="color:blue"&gt;Dim&lt;/span&gt; ctr &lt;span style="color:blue"&gt;As Integer&lt;/span&gt; = 0
         &lt;span style="color:blue"&gt;Dim&lt;/span&gt; match &lt;span style="color:blue"&gt;As&lt;/span&gt; &lt;span style="color:#2B91AF"&gt;Match&lt;/span&gt; = &lt;span style="color:#2B91AF"&gt;Regex&lt;/span&gt;.Match(input, pattern)
         &lt;span style="color:blue"&gt;Do While&lt;/span&gt; match.Success
            ctr += 1
            match = match.NextMatch()
         &lt;span style="color:blue"&gt;Loop&lt;/span&gt;

         sw.Stop()

         &lt;span style="color:green"&gt;' Display performance information.&lt;/span&gt;
         &lt;span style="color:#2B91AF"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#A31515"&gt;"'{0}' ({1} capturing groups): {2:N0} matches in {3:ss\.fffff}"&lt;/span&gt;,
                           regex.ToString(), regex.GetGroupNumbers().Length,
                           ctr, sw.Elapsed)
         &lt;span style="color:#2B91AF"&gt;Console&lt;/span&gt;.WriteLine()
      &lt;span style="color:blue"&gt;Next
   End Sub
End Module&lt;/span&gt;

[C#]
&lt;span style="color:blue"&gt;using&lt;/span&gt; System;

&lt;span style="color:blue"&gt;using&lt;/span&gt; System.Diagnostics;
&lt;span style="color:blue"&gt;using&lt;/span&gt; System.IO;
&lt;span style="color:blue"&gt;using&lt;/span&gt; System.Text.RegularExpressions;

&lt;span style="color:blue"&gt;public class&lt;/span&gt; &lt;span style="color:#2B91AF"&gt;Example&lt;/span&gt;
{
   &lt;span style="color:blue"&gt;public static void&lt;/span&gt; Main()
   {
      &lt;span style="color:blue"&gt;string&lt;/span&gt;[] patterns = { @&lt;span style="color:#A31515"&gt;"(\b(\w+)[;,]?\s?)+([.?!])"&lt;/span&gt;,
                            @&lt;span style="color:#A31515"&gt;"(?:\b(\w+)[;,]?\s?)+([.?!])"&lt;/span&gt;,
                            @&lt;span style="color:#A31515"&gt;"(?:\b(?:\w+)[;,]?\s?)+[.?!]"&lt;/span&gt; };
      &lt;span style="color:blue"&gt;string&lt;/span&gt; input = (&lt;span style="color:blue"&gt;new&lt;/span&gt; &lt;span style="color:#2B91AF"&gt;StreamReader&lt;/span&gt;(@&lt;span style="color:#A31515"&gt;".\Dreiser_TheFinancier.txt"&lt;/span&gt;)).ReadToEnd();
      &lt;span style="color:#2B91AF"&gt;Stopwatch&lt;/span&gt; sw;

      &lt;span style="color:blue"&gt;foreach&lt;/span&gt; (&lt;span style="color:blue"&gt;var&lt;/span&gt; pattern &lt;span style="color:blue"&gt;in&lt;/span&gt; patterns) {
         &lt;span style="color:green"&gt;// Instantiate the regular expression object before measuring performance.&lt;/span&gt;

         &lt;span style="color:#2B91AF"&gt;Regex&lt;/span&gt; regex = &lt;span style="color:blue"&gt;new&lt;/span&gt; &lt;span style="color:#2B91AF"&gt;Regex&lt;/span&gt;(pattern);

         &lt;span style="color:green"&gt;// Time matches.&lt;/span&gt;
         sw = &lt;span style="color:#2B91AF"&gt;Stopwatch&lt;/span&gt;.StartNew();

         &lt;span style="color:blue"&gt;int&lt;/span&gt; ctr = 0;
         &lt;span style="color:#2B91AF"&gt;Match&lt;/span&gt; match = &lt;span style="color:#2B91AF"&gt;Regex&lt;/span&gt;.Match(input, pattern);
         &lt;span style="color:blue"&gt;while&lt;/span&gt; (match.Success) {
            ctr++;
            match = match.NextMatch();
         }
         sw.Stop();

         &lt;span style="color:green"&gt;// Display performance information.&lt;/span&gt;

         &lt;span style="color:#2B91AF"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#A31515"&gt;"'{0}' ({1} capturing groups): {2:N0} matches in {3:ss\\.fffff}\n"&lt;/span&gt;,
                           regex.ToString(), regex.GetGroupNumbers().Length,
                           ctr, sw.Elapsed);
      }  
   }   
}
&lt;/pre&gt;
&lt;div&gt;&lt;/div&gt;
&lt;p&gt;As the following output from the example shows, populating the &lt;b&gt;GroupCollection&lt;/b&gt; and &lt;b&gt;CaptureCollection&lt;/b&gt; objects has a significant impact on the regular expression engine&amp;rsquo;s performance. The regular expression with three capturing groups executed slightly more than 15faster than the one with four capturing groups, and the regular expression with just one capturing group executed more than 25% faster than the one with four. The poorer performance of the regular expression with four capturing groups is a legitimate cost if programmatic access to these captures is required. However, if it is not, populating the complete regular expression object model constitutes unnecessary overhead.&lt;/p&gt;
&lt;div&gt;&lt;/div&gt;
&lt;pre&gt;'(\b(\w+)[;,]?\s?)+([.?!])' (4 capturing groups): 12,633 matches in 02.4953428
'(?:\b(\w+)[;,]?\s?)+([.?!])' (3 capturing groups): 12,633 matches in 02.0867863
'(?:\b(?:\w+)[;,]?\s?)+[.?!]' (1 capturing groups): 12,633 matches in 01.7976809
&lt;/pre&gt;
&lt;h2&gt;Capturing and Non-Capturing Grouping Constructs&lt;/h2&gt;
&lt;div&gt;&lt;/div&gt;
&lt;p&gt;The regular expression language in the .NET Framework supports a number of grouping constructs, which are documented in detail in the &lt;a href="http://msdn.microsoft.com/en-us/library/bs2twtah.aspx"&gt;Grouping Constructs&lt;/a&gt; topic in the MSDN Library. The following table lists each grouping construct and indicates whether it captures the text matched by the group. &lt;/p&gt;
&lt;div&gt;&lt;/div&gt;
&lt;table cellpadding="0" cellspacing="0" border="1" style="width: 90%;"&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td width="30%" valign="top" style="border:solid windowtext 1.0pt;padding:0in 5.4pt 0in 5.4pt"&gt;
&lt;div&gt;&lt;/div&gt;
&lt;b&gt;Language Element&lt;/b&gt;
&lt;div&gt;&lt;/div&gt;
&lt;/td&gt;
&lt;td width="45%" valign="top" style="border:solid windowtext 1.0pt;border-left:none;padding:0in 5.4pt 0in 5.4pt"&gt;
&lt;div&gt;&lt;/div&gt;
&lt;b&gt;Description&lt;/b&gt;
&lt;div&gt;&lt;/div&gt;
&lt;/td&gt;
&lt;td width="25%" valign="top" style="border:solid windowtext 1.0pt;border-left:none;padding:0in 5.4pt 0in 5.4pt"&gt;
&lt;div&gt;&lt;/div&gt;
&lt;b&gt;Capturing or Non-capturing&lt;/b&gt;
&lt;div&gt;&lt;/div&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td valign="top" style="border:solid windowtext 1.0pt;border-top:none;padding:0in 5.4pt 0in 5.4pt"&gt;
&lt;div&gt;&lt;/div&gt;
&lt;code&gt;(&lt;i&gt;subexpression&lt;/i&gt;)&lt;/code&gt;
&lt;div&gt;&lt;/div&gt;
&lt;/td&gt;
&lt;td valign="top" style="border-top:none;border-left:
          none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
          padding:0in 5.4pt 0in 5.4pt"&gt;
&lt;p&gt;Captures a group, which can be referenced by number or retrieved from the &lt;b&gt;GroupCollection&lt;/b&gt; object by its ordinal position.&lt;/p&gt;
&lt;/td&gt;
&lt;td valign="top" style="border-top:none;border-left:
          none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
          padding:0in 5.4pt 0in 5.4pt"&gt;
&lt;p&gt;Capturing&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td valign="top" style="border:solid windowtext 1.0pt;
          border-top:none;padding:0in 5.4pt 0in 5.4pt"&gt;
&lt;div&gt;&lt;/div&gt;
&lt;code&gt;(?&amp;lt;&lt;i&gt;name&lt;/i&gt;&amp;gt;&lt;i&gt;subexpression&lt;/i&gt;)&lt;/code&gt;
&lt;div&gt;&lt;/div&gt;
&lt;/td&gt;
&lt;td valign="top" style="border-top:none;border-left:
          none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
          padding:0in 5.4pt 0in 5.4pt"&gt;
&lt;p&gt;Captures a named group, which can be referenced by name or by number or retrieved from the GroupCollection object by its name or ordinal position.&lt;/p&gt;
&lt;/td&gt;
&lt;td valign="top" style="border-top:none;border-left:
          none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
          padding:0in 5.4pt 0in 5.4pt"&gt;
&lt;p&gt;Capturing&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td valign="top" style="border:solid windowtext 1.0pt;
          border-top:none;padding:0in 5.4pt 0in 5.4pt"&gt;
&lt;div&gt;&lt;/div&gt;
&lt;code&gt;(?&amp;lt;&lt;i&gt;name1&lt;/i&gt;-&lt;i&gt;name2&lt;/i&gt;&amp;gt;&lt;i&gt;subexpression&lt;/i&gt;)&lt;/code&gt;
&lt;div&gt;&lt;/div&gt;
&lt;/td&gt;
&lt;td valign="top" style="border-top:none;border-left:
          none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
          padding:0in 5.4pt 0in 5.4pt"&gt;
&lt;p&gt;Balancing group definition. Tracks nested constructs such as opening and closing parentheses or opening and closing brackets. Capturing groups is integral to the operation of this language element.&lt;/p&gt;
&lt;/td&gt;
&lt;td valign="top" style="border-top:none;border-left:
          none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
          padding:0in 5.4pt 0in 5.4pt"&gt;
&lt;p&gt;Capturing&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td valign="top" style="border:solid windowtext 1.0pt;border-top:none;padding:0in 5.4pt 0in 5.4pt"&gt;
&lt;div&gt;&lt;/div&gt;
&lt;code&gt;(?:&lt;i&gt;subexpression&lt;/i&gt;)&lt;/code&gt;
&lt;div&gt;&lt;/div&gt;
&lt;/td&gt;
&lt;td valign="top" style="border-top:none;border-left:none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
          padding:0in 5.4pt 0in 5.4pt"&gt;
&lt;p&gt;Non-capturing group. Typically, it is used to define a subexpression to which a quantifier can be applied.&lt;/p&gt;
&lt;/td&gt;
&lt;td valign="top" style="border-top:none;border-left:
          none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
          padding:0in 5.4pt 0in 5.4pt"&gt;
&lt;p&gt;Non-capturing&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td valign="top" style="border:solid windowtext 1.0pt;
          border-top:none;padding:0in 5.4pt 0in 5.4pt"&gt;
&lt;div&gt;&lt;/div&gt;
&lt;code&gt;(?imnsx-imnsx:&lt;i&gt;subexpression&lt;/i&gt;)&lt;/code&gt;
&lt;div&gt;&lt;/div&gt;
&lt;/td&gt;
&lt;td valign="top" style="border-top:none;border-left:
          none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
          padding:0in 5.4pt 0in 5.4pt"&gt;
&lt;p&gt;Defines options (such as case-sensitivity or the significance of white space) that apply to &lt;code&gt;&lt;i&gt;subexpression&lt;/i&gt;&lt;/code&gt;.&lt;/p&gt;
&lt;/td&gt;
&lt;td valign="top" style="border-top:none;border-left:
          none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
          padding:0in 5.4pt 0in 5.4pt"&gt;
&lt;p&gt;Non-capturing&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td valign="top" style="border:solid windowtext 1.0pt;
          border-top:none;padding:0in 5.4pt 0in 5.4pt"&gt;
&lt;div&gt;&lt;/div&gt;
&lt;code&gt;(?=&lt;i&gt;subexpression&lt;/i&gt;)&lt;/code&gt;
&lt;div&gt;&lt;/div&gt;
&lt;/td&gt;
&lt;td valign="top" style="border-top:none;border-left:
          none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
          padding:0in 5.4pt 0in 5.4pt"&gt;
&lt;p&gt;Positive lookahead assertion. Looks ahead of the current position in the input string to determine if &lt;code&gt;&lt;i&gt;subexpression&lt;/i&gt;&lt;/code&gt; is matched.&lt;/p&gt;
&lt;/td&gt;
&lt;td valign="top" style="border-top:none;border-left:
          none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
          padding:0in 5.4pt 0in 5.4pt"&gt;
&lt;p&gt;Non-capturing&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td valign="top" style="border:solid windowtext 1.0pt;
          border-top:none;padding:0in 5.4pt 0in 5.4pt"&gt;
&lt;div&gt;&lt;/div&gt;
&lt;code&gt;(?!&lt;i&gt;subexpression&lt;/i&gt;)&lt;/code&gt;
&lt;div&gt;&lt;/div&gt;
&lt;/td&gt;
&lt;td valign="top" style="border-top:none;border-left:
          none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
          padding:0in 5.4pt 0in 5.4pt"&gt;
&lt;p&gt;Negative lookahead assertion. Looks ahead of the current position in the input string to determine if &lt;code&gt;&lt;i&gt;subexpression&lt;/i&gt;&lt;/code&gt; is not matched.&lt;/p&gt;
&lt;/td&gt;
&lt;td valign="top" style="border-top:none;border-left:
          none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
          padding:0in 5.4pt 0in 5.4pt"&gt;
&lt;p&gt;Non-capturing&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td valign="top" style="border:solid windowtext 1.0pt;
          border-top:none;padding:0in 5.4pt 0in 5.4pt"&gt;
&lt;div&gt;&lt;/div&gt;
&lt;code&gt;(?&amp;lt;=&lt;i&gt;subexpression&lt;/i&gt;)&lt;code&gt;
&lt;div&gt;&lt;/div&gt;
&lt;/code&gt;&lt;/code&gt;&lt;/td&gt;
&lt;td valign="top" style="border-top:none;border-left:
          none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
          padding:0in 5.4pt 0in 5.4pt"&gt;
&lt;p class="MsoNormal"&gt;Positive lookbehind assertion. Looks behind the current position in the input string to determine if &lt;code&gt;&lt;i&gt;subexpression&lt;/i&gt; is matched.&lt;/code&gt;&lt;/p&gt;
&lt;/td&gt;
&lt;td valign="top" style="border-top:none;border-left:
          none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
          padding:0in 5.4pt 0in 5.4pt"&gt;
&lt;p&gt;Non-capturing&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td valign="top" style="border:solid windowtext 1.0pt;
          border-top:none;padding:0in 5.4pt 0in 5.4pt"&gt;
&lt;div&gt;&lt;/div&gt;
&lt;code&gt;(?&amp;lt;!&lt;i&gt;subexpression&lt;/i&gt;)&lt;/code&gt;
&lt;div&gt;&lt;/div&gt;
&lt;/td&gt;
&lt;td valign="top" style="border-top:none;border-left:
          none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
          padding:0in 5.4pt 0in 5.4pt"&gt;
&lt;p&gt;Negative lookbehind assertion. Looks behind the current position in the input string to determine if &lt;code&gt;&lt;i&gt;subexpression&lt;/i&gt;&lt;/code&gt; is not matched.&lt;/p&gt;
&lt;/td&gt;
&lt;td valign="top" style="border-top:none;border-left:
          none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
          padding:0in 5.4pt 0in 5.4pt"&gt;
&lt;p&gt;Non-capturing&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td valign="top" style="border:solid windowtext 1.0pt;
          border-top:none;padding:0in 5.4pt 0in 5.4pt"&gt;
&lt;div&gt;&lt;/div&gt;
&lt;code&gt;(?&amp;gt;&lt;i&gt;subexpression&lt;/i&gt;)&lt;/code&gt;
&lt;div&gt;&lt;/div&gt;
&lt;/td&gt;
&lt;td valign="top" style="border-top:none;border-left:
          none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
          padding:0in 5.4pt 0in 5.4pt"&gt;
&lt;p&gt;Non-backtracking subexpression. Does not surrender any characters from a matched subexpression to ensure that the regular expression pattern as a whole is matched.&lt;/p&gt;
&lt;/td&gt;
&lt;td valign="top" style="border-top:none;border-left:
          none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
          padding:0in 5.4pt 0in 5.4pt"&gt;
&lt;p&gt;Non-capturing&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;h2&gt;Disabling Captures&lt;/h2&gt;
&lt;div&gt;&lt;/div&gt;
&lt;p&gt;You can disable all captures in a group, or you can disable all but named captures. Unnamed captures can be disabled for a regular expression as a whole, for a part of a regular expression, or for a particular subexpression. &lt;/p&gt;
&lt;div&gt;&lt;/div&gt;
&lt;div&gt;&lt;/div&gt;
&lt;p&gt;As the previous example showed, the &lt;code&gt;(?:&lt;i&gt;subexpression&lt;/i&gt;)&lt;/code&gt; language construct disables captures by a group. It disables captures only for the group to which it applies; it does not disable captures by nested or inner groups. In the previous example, for instance, the regular expression pattern &lt;code&gt;(?:\b(\w+)[;,]?\s?)+([.?!])&lt;/code&gt; disables captures by the outer group (group 1). The inner group &lt;code&gt;(\w+)&lt;/code&gt; (group 2) is not affected and remains a capturing group.&lt;/p&gt;
&lt;div&gt;&lt;/div&gt;
&lt;div&gt;&lt;/div&gt;
&lt;p&gt;You can also control implicit captures by using regular expression language options. These options are specified either as members of the &lt;a href="http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regexoptions.aspx"&gt;&lt;b&gt;RegexOptions&lt;/b&gt; enumeration&lt;/a&gt; or as inline characters in an options language construct. For more information, see &lt;a href="http://msdn.microsoft.com/en-us/library/yd1hzczs.aspx"&gt;Regular Expression Options&lt;/a&gt;.&lt;/p&gt;
&lt;div&gt;&lt;/div&gt;
&lt;div&gt;&lt;/div&gt;
&lt;p&gt;The &lt;b&gt;RegexOptions.ExplicitCapture&lt;/b&gt; option or its corresponding &lt;code&gt;n&lt;/code&gt; language option can be used to disable all unnamed or implicit captures; only matches from named groups defined by the &lt;code&gt;(?&amp;lt;&lt;i&gt;name&lt;/i&gt;&amp;gt;&lt;i&gt;subexpression&lt;/i&gt;)&lt;/code&gt; language element are captured.&lt;/p&gt;
&lt;div&gt;&lt;/div&gt;
&lt;div&gt;&lt;/div&gt;
&lt;p&gt;The &lt;b&gt;RegexOptions.ExplicitCapture&lt;/b&gt; option disables implicit captures by the regular expression engine for a particular regular expression or for a particular matching operation. It disables implicit captures for the regular expression if it is passed to the &lt;b&gt;Regex&lt;/b&gt; class constructor, and it disables implicit captures for a particular matching operation if it is passed to a static &lt;b&gt;Regex&lt;/b&gt; matching method, such as &lt;b&gt;Regex.Match&lt;/b&gt; or &lt;b&gt;Regex.Matches&lt;/b&gt;. The following example illustrates this. It changes the previous regular expression pattern to &lt;code&gt;(\b(?&amp;lt;words&amp;gt;\w+)[;,]?\s?)+([.?!])&lt;/code&gt; so that it has two implicit capturing groups and one named capturing group. When the &lt;b&gt;Regex&lt;/b&gt; object is instantiated with its &lt;code&gt;&lt;i&gt;options&lt;/i&gt;&lt;/code&gt; parameter set to &lt;b&gt;RegexOptions.ExplicitCapture&lt;/b&gt;, only matches made by the named group are captured.&lt;/p&gt;
&lt;div&gt;&lt;/div&gt;
&lt;pre&gt;[Visual Basic]
&lt;span style="color:blue"&gt;Imports&lt;/span&gt; System.Text.RegularExpressions

&lt;span style="color:blue"&gt;Module&lt;/span&gt; &lt;span style="color:#2B91AF"&gt;Example&lt;/span&gt;

   &lt;span style="color:blue"&gt;Public Sub&lt;/span&gt; Main()
      &lt;span style="color:blue"&gt;Dim&lt;/span&gt; pattern &lt;span style="color:blue"&gt;As String&lt;/span&gt; = &lt;span style="color:#A31515"&gt;"(\b(?&amp;lt;words&amp;gt;\w+)[;,]?\s?)+([.?!])"&lt;/span&gt;
      &lt;span style="color:blue"&gt;Dim&lt;/span&gt; input &lt;span style="color:blue"&gt;As String&lt;/span&gt; = &lt;span style="color:#A31515"&gt;"This is a short, silly sentence."&lt;/span&gt;

      &lt;span style="color:blue"&gt;Dim&lt;/span&gt; rgx &lt;span style="color:blue"&gt;As New&lt;/span&gt; &lt;span style="color:#2B91AF"&gt;Regex&lt;/span&gt;(pattern, &lt;span style="color:#2B91AF"&gt;RegexOptions&lt;/span&gt;.ExplicitCapture)
      &lt;span style="color:blue"&gt;Dim&lt;/span&gt; match &lt;span style="color:blue"&gt;As&lt;/span&gt; &lt;span style="color:#2B91AF"&gt;Match&lt;/span&gt; = rgx.Match(input)

      &lt;span style="color:blue"&gt;If&lt;/span&gt; match.Success &lt;span style="color:blue"&gt;Then&lt;/span&gt;

         &lt;span style="color:#2B91AF"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#A31515"&gt;"'{0}' found at position {1}."&lt;/span&gt;, 
                           match.Value, match.Index)
         &lt;span style="color:#2B91AF"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#A31515"&gt;"There are {0} captured groups:"&lt;/span&gt;, 
                           match.Groups.Count)
         &lt;span style="color:blue"&gt;Dim&lt;/span&gt; ctr &lt;span style="color:blue"&gt;As Integer&lt;/span&gt; = 0
         &lt;span style="color:blue"&gt;For Each&lt;/span&gt; grp &lt;span style="color:blue"&gt;As&lt;/span&gt; &lt;span style="color:#2B91AF"&gt;Group&lt;/span&gt; &lt;span style="color:blue"&gt;In&lt;/span&gt; match.Groups
            &lt;span style="color:#2B91AF"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#A31515"&gt;"   Group &amp;lt;{0}&amp;gt;: '{1}' at position {2}."&lt;/span&gt;, 
                              rgx.GroupNameFromNumber(ctr), grp.Value,
                              grp.Index)
            &lt;span style="color:blue"&gt;Dim&lt;/span&gt; capCtr &lt;span style="color:blue"&gt;As Integer&lt;/span&gt; = 1
            &lt;span style="color:blue"&gt;For Each&lt;/span&gt; capture &lt;span style="color:blue"&gt;In&lt;/span&gt; grp.Captures
               &lt;span style="color:#2B91AF"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#A31515"&gt;"      Capture {0}: '{1}' at position {2}."&lt;/span&gt;, 
                                 capCtr, capture.Value, capture.Index)
               capCtr += 1
            &lt;span style="color:blue"&gt;Next&lt;/span&gt;

            ctr += 1
         &lt;span style="color:blue"&gt;Next
      End If
   End Sub
End Module&lt;/span&gt;

[C#]
&lt;span style="color:blue"&gt;using&lt;/span&gt; System;
&lt;span style="color:blue"&gt;using&lt;/span&gt; System.Text.RegularExpressions;

&lt;span style="color:blue"&gt;public class&lt;/span&gt; &lt;span style="color:#2B91AF"&gt;Example&lt;/span&gt;
{
   &lt;span style="color:blue"&gt;public static void&lt;/span&gt; Main()
   {
      &lt;span style="color:blue"&gt;string&lt;/span&gt; pattern = @&lt;span style="color:#A31515"&gt;"(\b(?&amp;lt;words&amp;gt;\w+)[;,]?\s?)+([.?!])"&lt;/span&gt;;
      &lt;span style="color:blue"&gt;string&lt;/span&gt; input = &lt;span style="color:#A31515"&gt;"This is a short, silly sentence."&lt;/span&gt;;
      &lt;span style="color:#2B91AF"&gt;Regex&lt;/span&gt; rgx = &lt;span style="color:blue"&gt;new&lt;/span&gt; &lt;span style="color:#2B91AF"&gt;Regex&lt;/span&gt;(pattern, &lt;span style="color:#2B91AF"&gt;RegexOptions&lt;/span&gt;.ExplicitCapture);
      &lt;span style="color:#2B91AF"&gt;Match&lt;/span&gt; match = rgx.Match(input);

      &lt;span style="color:blue"&gt;if&lt;/span&gt; (match.Success) {
         &lt;span style="color:#2B91AF"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#A31515"&gt;"'{0}' found at position {1}."&lt;/span&gt;,
                           match.Value, match.Index);
         &lt;span style="color:#2B91AF"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#A31515"&gt;"There are {0} captured groups:"&lt;/span&gt;,
                           match.Groups.Count);
         &lt;span style="color:blue"&gt;int&lt;/span&gt; ctr = 0;
         &lt;span style="color:blue"&gt;foreach&lt;/span&gt; (&lt;span style="color:#2B91AF"&gt;Group&lt;/span&gt; grp &lt;span style="color:blue"&gt;in&lt;/span&gt; match.Groups) {
            &lt;span style="color:#2B91AF"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#A31515"&gt;"   Group &amp;lt;{0}&amp;gt;: '{1}' at position {2}."&lt;/span&gt;,
                              rgx.GroupNameFromNumber(ctr++), grp.Value, 
                              grp.Index);
            &lt;span style="color:blue"&gt;int&lt;/span&gt; capCtr = 1;
            &lt;span style="color:blue"&gt;foreach&lt;/span&gt; (&lt;span style="color:#2B91AF"&gt;Capture&lt;/span&gt; capture &lt;span style="color:blue"&gt;in&lt;/span&gt; grp.Captures)  
               &lt;span style="color:#2B91AF"&gt;Console&lt;/span&gt;.WriteLine(&lt;span style="color:#A31515"&gt;"      Capture {0}: '{1}' at position {2}."&lt;/span&gt;,  
                                 capCtr++, capture.Value, capture.Index);
         }
      }
   }
}

&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;The example displays the following output:&lt;/p&gt;
&lt;div&gt;&lt;/div&gt;
&lt;pre&gt;'This is a short, silly sentence.' found at position 0.
There are 2 captured groups:
   Group &amp;lt;0&amp;gt;: 'This is a short, silly sentence.' at position 0.
      Capture 1: 'This is a short, silly sentence.' at position 0.
   Group &amp;lt;words&amp;gt;: 'sentence' at position 23.
      Capture 1: 'This' at position 0.
      Capture 2: 'is' at position 5.
      Capture 3: 'a' at position 8.
      Capture 4: 'short' at position 10.
      Capture 5: 'silly' at position 17.
      Capture 6: 'sentence' at position 23.
&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;You can also disable implicit captures for part of a regular expression pattern by using the &lt;code&gt;(?n:&lt;i&gt;subexpression&lt;/i&gt;)&lt;/code&gt; grouping construct. It disables implicit captures for all implicit groups defined in &lt;code&gt;&lt;i&gt;subexpression&lt;/i&gt;&lt;/code&gt;. If the construct is applied to the entire regular expression pattern, it is equivalent to instantiating a &lt;b&gt;Regex&lt;/b&gt; object with the &lt;b&gt;RegexOptions.ExplicitCapture&lt;/b&gt; option. For example, the output would remain unchanged if the regular expression pattern in the previous example were replaced by &lt;code&gt;(?n:(\b(?&amp;lt;words&amp;gt;\w+)[;,]?\s?)+([.?!]))&lt;/code&gt;. On the other hand, the regular expression pattern &lt;code&gt;(?n:((a+)(b+))+)(c.)&lt;/code&gt; disables captures in the subexpression &lt;code&gt;((a+)(b+))+)&lt;/code&gt;, including in the two nested expressions in the subexpression.&lt;/p&gt;
&lt;div&gt;&lt;/div&gt;
&lt;div&gt;&lt;/div&gt;
&lt;p&gt;The &lt;code&gt;(?n)&lt;/code&gt; inline element can also be used to disable implicit captures from the point that it is encountered in a regular expression to the end of the expression, or until the implicit captures only option is disabled by the &lt;code&gt;(?-n)&lt;/code&gt; inline option. (Note, though, that the &lt;code&gt;(?n:&lt;i&gt;subexpression&lt;/i&gt;)&lt;/code&gt; syntax can be used for the same result and is significantly clearer.) For example, the regular expression pattern &lt;code&gt;(?n)(\b(?&amp;lt;words&amp;gt;\w+)[;,]?\s?)+(?-n)([.?!])&lt;/code&gt; disables implicit captures in the subexpression &lt;code&gt;(\b(?&amp;lt;words&amp;gt;\w+)[;,]?\s?)+&lt;/code&gt; but enables them in the subexpression &lt;code&gt;([.?!])&lt;/code&gt;. As a result, a match has two capturing groups. The first captures the punctuation mark used to end a sentence. The second captures each word in the sentence.&lt;/p&gt;
&lt;div&gt;&lt;/div&gt;
&lt;h2&gt;Summary&lt;/h2&gt;
&lt;div&gt;&lt;/div&gt;
&lt;p&gt;The regular expression engine incurs a substantial performance hit when capturing groups appear in a regular expression. In cases where captures are not needed and grouping constructs are used primarily so that quantifiers can be applied to them, captures should be disabled. The regular expression language in the .NET Framework includes a non-capturing grouping construct, &lt;code&gt;(?:&lt;i&gt;subexpression&lt;/i&gt;)&lt;/code&gt;. In addition, implicit or unnamed captures can be disabled by supplying the &lt;b&gt;RegexOptions.ExplicitCapture&lt;/b&gt; option to a &lt;b&gt;Regex&lt;/b&gt; class constructor or static matching method, or by using the by using the &lt;code&gt;(?n:&lt;i&gt;subexpression&lt;/i&gt;)&lt;/code&gt; grouping construct or the &lt;code&gt;(?n)&lt;/code&gt; inline element.&lt;/p&gt;
&lt;div&gt;&lt;/div&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10146961" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/bclteam/archive/tags/RegEx/">RegEx</category></item><item><title>Announcing Portable Library Tools CTP [Justin Van Patten]</title><link>http://blogs.msdn.com/b/bclteam/archive/2011/01/19/announcing-portable-library-tools-ctp-justin-van-patten.aspx</link><pubDate>Wed, 19 Jan 2011 20:42:29 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10117835</guid><dc:creator>BCL Team</dc:creator><slash:comments>11</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/bclteam/rsscomments.aspx?WeblogPostID=10117835</wfw:commentRss><comments>http://blogs.msdn.com/b/bclteam/archive/2011/01/19/announcing-portable-library-tools-ctp-justin-van-patten.aspx#comments</comments><description>&lt;p&gt;Today we're announcing the CTP release of a new add-in for
Visual Studio 2010 that makes it easy to create C# and Visual Basic libraries
that run on a variety of .NET platforms without recompilation.&lt;/p&gt;
&lt;p&gt;Download the &lt;a href="http://go.microsoft.com/fwlink/?LinkID=206334&amp;amp;clcid=0x409"&gt;Portable
Library Tools CTP&lt;/a&gt; today (install &lt;a href="http://go.microsoft.com/fwlink/?LinkId=207130"&gt;VS 2010 SP1 Beta&lt;/a&gt; first).&lt;/p&gt;
&lt;h1&gt;Creating Portable Libraries&lt;/h1&gt;
&lt;p&gt;The Portable Library Tools CTP adds a new "Portable Class
Library" project template to Visual Studio that can be used to create class libraries
in C# and VB that run on the various .NET platforms without recompiling.&lt;/p&gt;
&lt;p&gt;&lt;img src="http://blogs.msdn.com/resized-image.ashx/__size/550x0/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-30-50/5224.plibproject.png" border="0" /&gt;&lt;/p&gt;
&lt;p&gt;Portable Class Library projects and assemblies can be
referenced and used by .NET 4, Silverlight 4, Windows Phone 7, and XNA for Xbox
360 projects.&lt;/p&gt;
&lt;h1&gt;Target Platforms Determine Available APIs&lt;/h1&gt;
&lt;p&gt;Within a Portable Class Library project, you can specify
which .NET platforms the library is intended to run on.&amp;nbsp; Although there is a 'core' set APIs that are
available on all platforms, there are also some APIs that are only available on
certain platforms.&amp;nbsp; An example of an API
that exists on some platforms but not others is MEF.&amp;nbsp; Windows Phone and Xbox 360 do not currently
have built-in support for MEF, but .NET and Silverlight do.&amp;nbsp; If you want to use MEF within a portable
library, the library will currently only run on .NET and Silverlight.&lt;/p&gt;
&lt;p&gt;Thus, the project's selected target platforms determine
which APIs can be used within the project.&amp;nbsp;
The APIs that are shown in intellisense and available to the compiler
are automatically filtered based on the selected target platforms, so you don't
need to have any special knowledge about each platform or worry about
inadvertently using an API that doesn't exist on a platform that you're
targeting.&amp;nbsp; The project system takes care
of this for you.&lt;/p&gt;
&lt;p&gt;In the future, as the underlying platforms evolve to support
more APIs that could be portable, we'll update the API surface available to
portable libraries as appropriate.&lt;/p&gt;
&lt;p&gt;The following table summarizes the high-level functionality currently
available on each platform:&lt;/p&gt;
&lt;table cellpadding="5" cellspacing="0" border="1"&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td valign="top"&gt;
&lt;p&gt;&lt;strong&gt;Feature&lt;/strong&gt;&lt;/p&gt;
&lt;/td&gt;
&lt;td valign="top"&gt;
&lt;p align="center"&gt;&lt;strong&gt;.NET&lt;/strong&gt;&lt;/p&gt;
&lt;/td&gt;
&lt;td valign="top"&gt;
&lt;p align="center"&gt;&lt;strong&gt;Silverlight&lt;/strong&gt;&lt;/p&gt;
&lt;/td&gt;
&lt;td valign="top"&gt;
&lt;p align="center"&gt;&lt;strong&gt;Windows Phone&lt;/strong&gt;&lt;/p&gt;
&lt;/td&gt;
&lt;td valign="top"&gt;
&lt;p align="center"&gt;&lt;strong&gt;Xbox 360&lt;/strong&gt;&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td valign="top"&gt;
&lt;p&gt;Core BCL&lt;/p&gt;
&lt;/td&gt;
&lt;td valign="top"&gt;
&lt;p align="center"&gt;Yes&lt;/p&gt;
&lt;/td&gt;
&lt;td valign="top"&gt;
&lt;p align="center"&gt;Yes&lt;/p&gt;
&lt;/td&gt;
&lt;td valign="top"&gt;
&lt;p align="center"&gt;Yes&lt;/p&gt;
&lt;/td&gt;
&lt;td valign="top"&gt;
&lt;p align="center"&gt;Yes&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td valign="top"&gt;
&lt;p&gt;Core XML&lt;/p&gt;
&lt;/td&gt;
&lt;td valign="top"&gt;
&lt;p align="center"&gt;Yes&lt;/p&gt;
&lt;/td&gt;
&lt;td valign="top"&gt;
&lt;p align="center"&gt;Yes&lt;/p&gt;
&lt;/td&gt;
&lt;td valign="top"&gt;
&lt;p align="center"&gt;Yes&lt;/p&gt;
&lt;/td&gt;
&lt;td valign="top"&gt;
&lt;p align="center"&gt;Yes&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td valign="top"&gt;
&lt;p&gt;Core HTTP&lt;/p&gt;
&lt;/td&gt;
&lt;td valign="top"&gt;
&lt;p align="center"&gt;Yes&lt;/p&gt;
&lt;/td&gt;
&lt;td valign="top"&gt;
&lt;p align="center"&gt;Yes&lt;/p&gt;
&lt;/td&gt;
&lt;td valign="top"&gt;
&lt;p align="center"&gt;Yes&lt;/p&gt;
&lt;/td&gt;
&lt;td valign="top"&gt;
&lt;p align="center"&gt;-&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td valign="top"&gt;
&lt;p&gt;WCF Client&lt;/p&gt;
&lt;/td&gt;
&lt;td valign="top"&gt;
&lt;p align="center"&gt;Yes&lt;/p&gt;
&lt;/td&gt;
&lt;td valign="top"&gt;
&lt;p align="center"&gt;Yes&lt;/p&gt;
&lt;/td&gt;
&lt;td valign="top"&gt;
&lt;p align="center"&gt;Yes&lt;/p&gt;
&lt;/td&gt;
&lt;td valign="top"&gt;
&lt;p align="center"&gt;-&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td valign="top"&gt;
&lt;p&gt;MEF&lt;/p&gt;
&lt;/td&gt;
&lt;td valign="top"&gt;
&lt;p align="center"&gt;Yes&lt;/p&gt;
&lt;/td&gt;
&lt;td valign="top"&gt;
&lt;p align="center"&gt;Yes&lt;/p&gt;
&lt;/td&gt;
&lt;td valign="top"&gt;
&lt;p align="center"&gt;-&lt;/p&gt;
&lt;/td&gt;
&lt;td valign="top"&gt;
&lt;p align="center"&gt;-&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Note: Once you've installed the Portable Library Tools CTP,
you can use the Object Browser in Visual Studio for a more in-depth look at the
individual APIs available for use within portable libraries.&lt;/p&gt;
&lt;p&gt;You can write a surprising amount of portable code with the
subset of APIs currently available to portable libraries. &amp;nbsp;Everything from business logic to web service
client proxies can be portable.&amp;nbsp; This
enables you to implement most, if not all, application logic in portable
assemblies (and then use the portable assemblies in apps that have
form-factor-specific UIs for a given platform).&lt;/p&gt;
&lt;p&gt;We're still in the process of defining the APIs that will be
available to portable libraries, so expect some minor tweaks and additions before
the final release of the tools.&amp;nbsp; We'd
love to get your feedback on what's currently available in the CTP.&amp;nbsp; Is there anything you think is missing that
should be available to portable libraries?&amp;nbsp;
How easy was it to make your existing libraries portable?&lt;/p&gt;
&lt;h1&gt;Known Limitations in the CTP&lt;/h1&gt;
&lt;h2&gt;Deploying Portable Libraries&lt;/h2&gt;
&lt;p&gt;The CTP of the Portable Library Tools is not a "go live"
release.&amp;nbsp; There are still some rough
edges that need smoothing out before the final release.&amp;nbsp; One area that does not currently have a
complete experience is around deploying portable libraries.&lt;/p&gt;
&lt;p&gt;Making portable libraries work on platforms such as .NET
Framework 4 and Silverlight 4 required making some minor changes to those
platforms.&amp;nbsp; In order for portable
libraries to work correctly on these platforms, you'll need to ensure the
necessary updates have been applied.&amp;nbsp;
Silverlight for Windows Phone 7 and XNA Framework 4.0 for Xbox 360 do
not require any updates to run portable assemblies.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;&lt;span style="text-decoration: underline;"&gt;.NET Framework 4
Update&lt;/span&gt;&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;An update to .NET Framework 4 is required to run portable
libraries.&amp;nbsp; For developers, this update
is automatically installed as part of Visual Studio SP1 Beta, so you shouldn't
need to install it on a machine that already has VS 2010 SP1 installed.&amp;nbsp; A standalone beta of this update is currently
available for download &lt;a href="http://www.microsoft.com/downloads/en/details.aspx?FamilyID=6e3b7759-3df2-4755-8208-44955eee4d4c"&gt;here&lt;/a&gt;.&amp;nbsp; The final release of the Portable Library
Tools will provide a way for developers to add a prerequisite to their
installer to ensure the update is applied on end-user machines when your app is
deployed.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;&lt;span style="text-decoration: underline;"&gt;Silverlight 4
Update&lt;/span&gt;&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;An update to Silverlight 4 is required to run portable
libraries.&amp;nbsp; This update hasn't been
released yet, but the impact in the meantime should be limited.&amp;nbsp; As long as you avoid using the following APIs
in your portable libraries, they will run just fine on Silverlight 4 without
the update:&lt;/p&gt;
&lt;ul class="unIndentedList"&gt;
&lt;li&gt;
System.Xml.XmlReader.Dispose&lt;/li&gt;
&lt;li&gt;
System.Xml.XmlWriter.Dispose&lt;/li&gt;
&lt;li&gt;
System.Net.WebResponse.Dispose&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;In the meantime, if you need to dispose these objects, you
can wrap them in a using statement or cast the object to IDisposable before
calling Dispose.&lt;/p&gt;
&lt;p&gt;Once the Silverlight 4 update is available, we will provide
instructions on how to specify it as the minimum version required for your
application.&lt;/p&gt;
&lt;h2&gt;Visual Basic Support&lt;/h2&gt;
&lt;p&gt;The Add Service Reference is currently disabled for VB
projects.&amp;nbsp; This will be resolved in a
future update.&lt;/p&gt;
&lt;h1&gt;Summary&lt;/h1&gt;
&lt;p&gt;We're excited to make a CTP of the &lt;a href="http://go.microsoft.com/fwlink/?LinkID=206334&amp;amp;clcid=0x409"&gt;Portable
Library Tools&lt;/a&gt; available for you to try out.&amp;nbsp;
Download the CTP today and let us know what you think!&lt;/p&gt;
&lt;p&gt;Also, you may be interested in watching Shawn Burke's PDC
2010 session on &lt;a href="http://player.microsoftpdc.com/Session/638f610a-ea51-4aef-9657-e3fe425ae745"&gt;3-Screen
Coding: Sharing code between Windows Phone, Silverlight, and .NET&lt;/a&gt;, which
provides some more background on portable libraries.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10117835" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/bclteam/archive/tags/News/">News</category><category domain="http://blogs.msdn.com/b/bclteam/archive/tags/Silverlight/">Silverlight</category><category domain="http://blogs.msdn.com/b/bclteam/archive/tags/-NET+Framework+4/">.NET Framework 4</category><category domain="http://blogs.msdn.com/b/bclteam/archive/tags/XNA/">XNA</category><category domain="http://blogs.msdn.com/b/bclteam/archive/tags/Windows+Phone/">Windows Phone</category></item><item><title>Time-travel with .NET or DateTime, DateTimeOffset and the lost DST hour [Greg]</title><link>http://blogs.msdn.com/b/bclteam/archive/2010/11/28/time-travel-with-net-or-datetime-datetimeoffset-and-the-lost-dst-hour-greg.aspx</link><pubDate>Sun, 28 Nov 2010 20:05:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10097520</guid><dc:creator>BCL Team</dc:creator><slash:comments>3</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/bclteam/rsscomments.aspx?WeblogPostID=10097520</wfw:commentRss><comments>http://blogs.msdn.com/b/bclteam/archive/2010/11/28/time-travel-with-net-or-datetime-datetimeoffset-and-the-lost-dst-hour-greg.aspx#comments</comments><description>&lt;p&gt;Every year again comes the DST change...&lt;/p&gt;  &lt;p&gt;And every year again do we need to work with customers on helping them understand some legacy design decisions, and how to work around these ghosts of the past.&lt;/p&gt;  &lt;p&gt;Recently, around the end of October and the start of November the daylight saving time (&lt;a title="Wikipedia article on Daylight Saving Time" href="http://en.wikipedia.org/wiki/Daylight_saving_time"&gt;DST&lt;/a&gt;) period finished in most areas of the northern hemisphere. As if it was an attempt to make up for the oncoming cold weather, we set our clocks back and got an extra hour of sleep. (In the southern hemisphere, the DST begins at the end of the year, and they turn their clocks forwards.) And one of the basic .NET types – &lt;code style="color: #0070c0; font-weight: bold"&gt;DateTime&lt;/code&gt; – does not play well with the annual end-of-DST transition. This issue is well-known and so is the workaround, but nevertheless it gets reported to us regularly by customers who rediscover the issue, especially around the DST transition season. There are a number of resources that treat this topic in great detail. Some of these resources are listed &lt;a href="#further-reading"&gt;below&lt;/a&gt;. Here, I provide some of the background for the reasons behind the issues and a brief refresher on how to solve the problems.&lt;/p&gt;  &lt;p style="border-bottom: black 1px solid; border-left: black 1px solid; padding-bottom: 10px; margin: 5px 40px; padding-left: 10px; padding-right: 10px; border-top: black 1px solid; border-right: black 1px solid; padding-top: 10px"&gt;First the gist: The &lt;code style="color: #0070c0; font-weight: bold"&gt;DateTimeOffset&lt;/code&gt; type helps avoiding most of the problems associated with &lt;code style="color: #0070c0; font-weight: bold"&gt;DateTime&lt;/code&gt;. If you have trouble with &lt;code style="color: #0070c0; font-weight: bold"&gt;DateTime&lt;/code&gt; in the context of a DST transition, consider using &lt;code style="color: #0070c0; font-weight: bold"&gt;DateTimeOffset&lt;/code&gt; instead.&lt;/p&gt;  &lt;h2&gt;Issue: Incorrect time zone display.&lt;/h2&gt;  &lt;p&gt;One issue with the &lt;code style="color: #0070c0; font-weight: bold"&gt;DateTime&lt;/code&gt; structure is that during transition from summer time to winter time (i.e. from DST to no-DST), the winter-time time-zone-offset it displayed an hour too early (when shown using a default built-in functionality such as &lt;code style="color: #0070c0; font-weight: bold"&gt;DateTime&lt;/code&gt;&lt;code style="color: #ff00ff; font-weight: bold"&gt;.&lt;/code&gt;&lt;code style="color: #000000; font-weight: bold"&gt;Now&lt;/code&gt;&lt;code style="color: #ff00ff; font-weight: bold"&gt;.&lt;/code&gt;&lt;code style="color: #000000; font-weight: bold"&gt;ToString(&lt;/code&gt;&lt;code style="color: #008000; font-weight: bold"&gt;&amp;quot;o&amp;quot;&lt;/code&gt;&lt;code style="color: #000000; font-weight: bold"&gt;)&lt;/code&gt; ). However, the actual clock time is always displayed correctly. This symptom is caused by the interplay of the fact that &lt;code style="color: #0070c0; font-weight: bold"&gt;DateTime&lt;/code&gt; stores the local time only, and the nature of DST transitions.&lt;/p&gt;  &lt;p&gt;Similar to the &lt;code style="color: #0070c0; font-weight: bold"&gt;DateTime&lt;/code&gt; type, the Windows DST database, on which Windows and .NET applications base their time calculations, specifies the transition times in local time (not UTC). During summer-to-winter time transition in the northern hemisphere the clocks are typically set one hour back. Assume, w.l.o.g., that the transition occurs at 3:00. Then, the times between 2:00 and 2:59 will occur twice: once during summer time, and once again during winter time after the clock has been set back. When the system is queried whether a time, say, 2:28, is in summer (say UTC -7) or in winter time (UTC -8), there is no way for the system to know which one is correct. In such cases, .NET assumes winter time, as that is typically the default time for the time zone (i.e. no DST). Note that if we changed this behaviour, the problem would still occur, only the other way around. For instance, the old DST state would show up one hour too long.&lt;/p&gt;  &lt;p&gt;In this particular case, the actual time is always shown correctly, it is just the DST state that is incorrect.&lt;/p&gt;  &lt;h2&gt;Solution: Track the DST mode changes.&lt;/h2&gt;  &lt;p&gt;At one second past the hour (or any other pre-specified time), store the local system time. Then compare the current time against the timestamp stored when the one-second-part-the-hour event occurred previously. If they match, we know that we just transitioned to winter time: the offset has changed (e.g. using the previous example, to UTC-8). Otherwise, we are still in summer time: it is still UTC-7.&lt;/p&gt;  &lt;p&gt;This workaround is complex and applies only to applications that run for at least one hour. This is not the best approach for a general fix.&lt;/p&gt;  &lt;h2&gt;Better solution: Use a type that stores time as UTC instead of local time.&lt;/h2&gt;  &lt;p&gt;UTC (&lt;a title="Wikipedia article on UTC" href="http://en.wikipedia.org/wiki/Coordinated_Universal_Time"&gt;coordinated universal time&lt;/a&gt;) describes the time at the Greenwich meridian and does not undergo any DST transitions. In a way (simplified but appropriate for this context), it can be understood as the “universal cosmological time”. The &lt;code style="color: #0070c0; font-weight: bold"&gt;DateTimeOffset&lt;/code&gt; type stores the local time as a pair of values: one value describes the UTC time, and the other value describes the offset between UTC and the local time. For instance, 02:28 in the UTC-7 time zone is stored as &lt;span style="white-space: nowrap"&gt;{&lt;em&gt;UtcTime - Offset&lt;/em&gt;} = {&lt;em&gt;10:28 - 420minutes&lt;/em&gt;}&lt;/span&gt;. 02:28 in the UTC-8 time zone is stored as &lt;span style="white-space: nowrap"&gt;{&lt;em&gt;11:28 - 480minutes&lt;/em&gt;}&lt;/span&gt;. In contrast to &lt;code style="color: #0070c0; font-weight: bold"&gt;DateTime&lt;/code&gt;, these two values, although describing the same local time, describe two different points in time, and can be easily differentiated from each other. As a result, issues related to DST transitions can be handled correctly when using &lt;code style="color: #0070c0; font-weight: bold"&gt;DateTimeOffset&lt;/code&gt;.&lt;/p&gt;  &lt;h2&gt;Putting it all together: Recommendations.&lt;/h2&gt;  &lt;p&gt;The reading list &lt;a href="#further-reading"&gt;below&lt;/a&gt; contains a wealth of background information on the &lt;code style="color: #0070c0; font-weight: bold"&gt;DateTime&lt;/code&gt; and &lt;code style="color: #0070c0; font-weight: bold"&gt;DateTimeOffset&lt;/code&gt; types and how to use them. Here is a short and practical summary of how these types should be used.&lt;/p&gt;  &lt;table&gt;&lt;tbody&gt;     &lt;tr&gt;       &lt;th width="50%"&gt;Use &lt;code style="color: #0070c0; font-weight: bold"&gt;DateTime&lt;/code&gt; to: &lt;/th&gt;        &lt;th width="50%"&gt;Use &lt;code style="color: #0070c0; font-weight: bold"&gt;DateTimeOffset&lt;/code&gt; to: &lt;/th&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td valign="top"&gt;         &lt;ul&gt;           &lt;li&gt;Represent dates only (no time information). &lt;/li&gt;            &lt;li&gt;Represent times only (not on a specific date).              &lt;br /&gt;(Alternatively, consider using the &lt;code style="color: #0070c0; font-weight: bold"&gt;TimeSpan&lt;/code&gt; type to represent the time of day without a specific date context). &lt;/li&gt;            &lt;li&gt;Work with abstract times and dates, such as historical dates. &lt;/li&gt;            &lt;li&gt;Work with legacy APIs that do not support &lt;code style="color: #0070c0; font-weight: bold"&gt;DateTimeOffset&lt;/code&gt; (e.g. some database and file system APIs). &lt;/li&gt;         &lt;/ul&gt;       &lt;/td&gt;        &lt;td valign="top"&gt;         &lt;ul&gt;           &lt;li&gt;Uniquely and unambiguously identify a single point in time. &lt;/li&gt;            &lt;li&gt;Log events occurring at specific times. &lt;/li&gt;            &lt;li&gt;Perform general date and time arithmetic. &lt;/li&gt;            &lt;li&gt;Work with time zones. &lt;/li&gt;            &lt;li&gt;Work with daylight saving times. &lt;/li&gt;         &lt;/ul&gt;       &lt;/td&gt;     &lt;/tr&gt;   &lt;/tbody&gt;&lt;/table&gt;  &lt;p&gt;More guidance on choosing the best date and time type for your circumstances is provided through the links below.&lt;/p&gt;  &lt;h2&gt;Further reading:&lt;/h2&gt; &lt;a name="further-reading"&gt;&lt;/a&gt;  &lt;ul&gt;   &lt;li&gt;&lt;a title="API Documentation" href="http://msdn.microsoft.com/en-us/library/system.datetimeoffset.aspx"&gt;The System.DateTimeOffset structure&lt;/a&gt;. &lt;/li&gt;    &lt;li&gt;&lt;a title="API Documentation" href="http://msdn.microsoft.com/en-us/library/system.datetime.aspx"&gt;The System.DateTime structure&lt;/a&gt;. &lt;/li&gt;    &lt;li&gt;&lt;a title="MSDN Knowledge Article" href="http://msdn.microsoft.com/en-us/library/bb384267.aspx"&gt;Choosing Between DateTime, DateTimeOffset, and TimeZoneInfo&lt;/a&gt;. &lt;/li&gt;    &lt;li&gt;&lt;a title="Previous BCL blog post" href="http://blogs.msdn.com/b/bclteam/archive/2007/06/14/datetimeoffset-a-new-datetime-structure-in-net-3-5-justin-van-patten.aspx"&gt;DateTimeOffset: A New DateTime Structure in .NET 3.5&lt;/a&gt;. &lt;/li&gt;    &lt;li&gt;&lt;a title="Previous BCL blog post" href="http://blogs.msdn.com/b/bclteam/archive/2007/06/18/a-brief-history-of-datetime-anthony-moore.aspx"&gt;A Brief History of DateTime&lt;/a&gt;. &lt;/li&gt;    &lt;li&gt;&lt;a title="Previous BCL blog post" href="http://blogs.msdn.com/b/bclteam/archive/2007/07/12/a-brief-history-of-datetime-follow-up-anthony-moore.aspx"&gt;A Brief History of DateTime Follow-up&lt;/a&gt;. &lt;/li&gt;    &lt;li&gt;&lt;a title="Previous BCL blog post" href="http://blogs.msdn.com/b/bclteam/archive/2004/05/21/136918.aspx"&gt;DateTime FAQ Entries&lt;/a&gt;. &lt;/li&gt;    &lt;li&gt;&lt;a title="Previous BCL blog post" href="http://blogs.msdn.com/b/bclteam/archive/2007/06/12/datetime-touniversaltime-returns-maxvalue-minvalue-on-overflow-josh-free.aspx"&gt;DateTime.ToUniversalTime returns MaxValue/MinValue on overflow&lt;/a&gt;. &lt;/li&gt;    &lt;li&gt;&lt;a title="Previous BCL blog post" href="http://blogs.msdn.com/b/bclteam/archive/2006/04/03/567119.aspx"&gt;Time Zones in the .NET Framework&lt;/a&gt;. &lt;/li&gt;    &lt;li&gt;&lt;a title="Previous BCL blog post" href="http://blogs.msdn.com/b/bclteam/archive/2007/06/11/system-timezoneinfo-working-with-ambiguous-and-invalid-points-in-time-josh-free.aspx"&gt;TimeZoneInfo: Working with Ambiguous and Invalid Points in Time&lt;/a&gt;. &lt;/li&gt; &lt;/ul&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10097520" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/bclteam/archive/tags/Globalization/">Globalization</category><category domain="http://blogs.msdn.com/b/bclteam/archive/tags/Time+and+Calendar/">Time and Calendar</category></item><item><title>The Caveats of Time Zone Names [Greg]</title><link>http://blogs.msdn.com/b/bclteam/archive/2010/10/11/the-caveats-of-time-zone-names.aspx</link><pubDate>Tue, 12 Oct 2010 01:18:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10074441</guid><dc:creator>BCL Team</dc:creator><slash:comments>4</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/bclteam/rsscomments.aspx?WeblogPostID=10074441</wfw:commentRss><comments>http://blogs.msdn.com/b/bclteam/archive/2010/10/11/the-caveats-of-time-zone-names.aspx#comments</comments><description>&lt;p&gt;Hi Everyone!&lt;/p&gt;
&lt;p&gt;My name is Greg, I joined the NetFx Base Class Libraries (BCL) team a few months ago, and I am really excited about my work on some very cool new framework features. Before joining the BCL team I was working in academic research in complex systems, network theory and artificial life at Monash University in Australia, and previously I was running a small software development and consulting company with clients in Germany and the UK.&lt;/p&gt;
&lt;p&gt;Besides adding some awesome new stuff to the next release for the framework (can&amp;rsquo;t talk about that yet!) I am also maintaining and improving some of the existing namespaces. This involves fixing some bugs and helping our customers by explaining how to use the framework on the &lt;a href="http://connect.microsoft.com/VisualStudio"&gt;Connect portal&lt;/a&gt;. There are a few issues that come up regularly and are particularly tricky to deal with, so I would like to talk about them briefly to a wider audience and in a more generic context (i.e. here). Today I will be talking about time zones and, in particular, potential pitfalls associated with their naming.&lt;/p&gt;
&lt;p&gt;In .NET, the class that provides most of the functionality for dealing with time zones, converting times from one zone to another, and working with &lt;a href="http://en.wikipedia.org/wiki/Daylight_saving_time"&gt;daylight saving time&lt;/a&gt; (DST), is &lt;a href="http://msdn.microsoft.com/en-us/library/system.timezoneinfo.aspx"&gt;System.TimeZoneInfo&lt;/a&gt;. In turn, the data that &lt;span style="font-family: Consolas;"&gt;TimeZoneInfo&lt;/span&gt; uses for its calculations is provided by Windows in the registry under this key:&lt;/p&gt;
&lt;p&gt;&lt;span style="font-family: Consolas;"&gt;HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones&lt;/span&gt;&lt;/p&gt;
&lt;p&gt;(Note: be very careful if you touch the registry, never change anything if you are not absolutely sure what you are doing, and always create a back-up before your changes.)&lt;/p&gt;
&lt;p&gt;In order to access information about a specific time zone in a .NET application, you need to instantiate a &lt;span style="font-family: Consolas;"&gt;TimeZoneInfo&lt;/span&gt; object that represents that time zone using the factory method &lt;a href="http://msdn.microsoft.com/en-us/library/system.timezoneinfo.findsystemtimezonebyid.aspx"&gt;TimeZoneInfo.FindSystemTimeZoneById(String id)&lt;/a&gt; (see also &lt;a href="http://msdn.microsoft.com/en-us/library/bb397765.aspx"&gt;here&lt;/a&gt; for more information). That factory method takes a string parameter specifying a time zone name and returns a &lt;span style="font-family: Consolas;"&gt;TimeZoneInfo&lt;/span&gt; instance that represents the specified time zone. It provides information including offset from the &lt;a href="http://en.wikipedia.org/wiki/Coordinated_Universal_Time"&gt;universal standard time&lt;/a&gt; (UTC), information about &lt;a href="http://en.wikipedia.org/wiki/Daylight_saving_time"&gt;DST&lt;/a&gt; adjustments, time conversion routines and more. &lt;/p&gt;
&lt;p&gt;The difficulty is in providing the correct ID (name) of a time zone in order to get hold of the corresponding object: The naming for the time zones is not always intuitive. As a result, it is easy to get confused and to create program bugs and unexpected behaviour. Consider for instance the zone named &lt;span style="font-family: Consolas;"&gt;"US Eastern Standard Time"&lt;/span&gt;. Unexpectedly this is &lt;i&gt;not&lt;/i&gt; the &lt;a href="http://en.wikipedia.org/wiki/Eastern_Time_Zone"&gt;EST/EDT&lt;/a&gt; observed on most of the US east coast. Instead, it is a &lt;a href="http://en.wikipedia.org/wiki/Indiana#Time_zones"&gt;US-Indiana-Only time zone&lt;/a&gt; that is not used any more since 2006 and does not change to DST. The name of the time zone that people are probably looking for instead is "Eastern Standard Time". That is the ID you need to get the &lt;span style="font-family: Consolas;"&gt;TimeZoneInfo&lt;/span&gt; object that represents the time zone used in most of east North America. That time zone &lt;i&gt;does&lt;/i&gt; use DST.&lt;/p&gt;
&lt;p&gt;Another time zone with a misleading name is &lt;span style="font-family: Consolas;"&gt;&lt;span style="font-family: Consolas;"&gt;"&lt;/span&gt;Greenwich Standard Time&lt;span style="font-family: Consolas;"&gt;"&lt;/span&gt;&lt;/span&gt;. This zone applies to places like Monrovia (Liberia) and Reykjavik (Island). These places do &lt;i&gt;not&lt;/i&gt; observe DST in 2010. This zone is easily confused with &lt;span style="font-family: Consolas;"&gt;"GMT Standard Time"&lt;/span&gt; that contains Portugal and the UK and &lt;i&gt;does&lt;/i&gt; observe DST.&lt;/p&gt;
&lt;p&gt;To exemplify the issue, consider the following code sample. Its output is given below.&lt;/p&gt;
&lt;pre class="code" style="font-family: consolas"&gt;&lt;span style="color: maroon"&gt;using&lt;/span&gt;&amp;nbsp;System;
 
&lt;span style="color: maroon"&gt;namespace&lt;/span&gt;&amp;nbsp;Microsoft&lt;span style="color: magenta;"&gt;.&lt;/span&gt;Misc&lt;span style="color: magenta"&gt;.&lt;/span&gt;MSDNBlog&amp;nbsp;{
&lt;span style="color: maroon"&gt;public&lt;/span&gt;&amp;nbsp;&lt;span style="color: maroon"&gt;static&lt;/span&gt;&amp;nbsp;&lt;span style="color: maroon;"&gt;class&lt;/span&gt;&amp;nbsp;&lt;span style="color: navy"&gt;ConfusingTimeZoneNames_Demo&lt;/span&gt;&amp;nbsp;{
 
&lt;span style="color: maroon"&gt;private&lt;/span&gt;&amp;nbsp;&lt;span style="color: maroon"&gt;static&lt;/span&gt;&amp;nbsp;&lt;span style="color: navy;"&gt;String&lt;/span&gt;[]&amp;nbsp;zoneIDs&amp;nbsp;&lt;span style="color: magenta"&gt;=&lt;/span&gt;&amp;nbsp;&lt;span style="color: maroon;"&gt;new&lt;/span&gt;&amp;nbsp;&lt;span style="color: navy"&gt;String&lt;/span&gt;[]&amp;nbsp;{
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: green"&gt;"China&amp;nbsp;Standard&amp;nbsp;Time"&lt;/span&gt;,
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: green"&gt;"AUS&amp;nbsp;Eastern&amp;nbsp;Standard&amp;nbsp;Time"&lt;/span&gt;,
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: green"&gt;"Pacific&amp;nbsp;Standard&amp;nbsp;Time"&lt;/span&gt;,
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: green"&gt;"US&amp;nbsp;Eastern&amp;nbsp;Standard&amp;nbsp;Time"&lt;/span&gt;,
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: green"&gt;"Eastern&amp;nbsp;Standard&amp;nbsp;Time"&lt;/span&gt;,
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: green"&gt;"Greenwich&amp;nbsp;Standard&amp;nbsp;Time"&lt;/span&gt;,
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: green"&gt;"GMT&amp;nbsp;Standard&amp;nbsp;Time"&lt;/span&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;};
 
 
&lt;span style="color: maroon"&gt;public&lt;/span&gt;&amp;nbsp;&lt;span style="color: maroon"&gt;static&lt;/span&gt;&amp;nbsp;&lt;span style="color: maroon;"&gt;void&lt;/span&gt;&amp;nbsp;Main(&lt;span style="color: navy"&gt;String&lt;/span&gt;[]&amp;nbsp;unusedArgs)&amp;nbsp;{
 
&amp;nbsp;&amp;nbsp;&lt;span style="color: maroon"&gt;const&lt;/span&gt;&amp;nbsp;&lt;span style="color: navy"&gt;String&lt;/span&gt;&amp;nbsp;format&amp;nbsp;&lt;span style="color: magenta;"&gt;=&lt;/span&gt;&amp;nbsp;&lt;span style="color: green"&gt;"{0,-26}&amp;nbsp;|&amp;nbsp;{1}&amp;nbsp;{2}|&amp;nbsp;{3}"&lt;/span&gt;;
&amp;nbsp;&amp;nbsp;&lt;span style="color: #2b91af"&gt;DateTime&lt;/span&gt;&amp;nbsp;utcTime&amp;nbsp;&lt;span style="color: magenta;"&gt;=&lt;/span&gt;&amp;nbsp;&lt;span style="color: maroon"&gt;new&lt;/span&gt;&amp;nbsp;&lt;span style="color: #2b91af;"&gt;DateTime&lt;/span&gt;(&lt;span style="color: purple"&gt;2010&lt;/span&gt;,&amp;nbsp;&lt;span style="color: purple;"&gt;06&lt;/span&gt;,&amp;nbsp;&lt;span style="color: purple"&gt;01&lt;/span&gt;,&amp;nbsp;&lt;span style="color: purple;"&gt;12&lt;/span&gt;,&amp;nbsp;&lt;span style="color: purple"&gt;30&lt;/span&gt;,&amp;nbsp;&lt;span style="color: purple;"&gt;0&lt;/span&gt;);
 
&amp;nbsp;&amp;nbsp;&lt;span style="color: navy"&gt;Console&lt;/span&gt;&lt;span style="color: magenta"&gt;.&lt;/span&gt;WriteLine(format,&amp;nbsp;&lt;span style="color: green;"&gt;"Time&amp;nbsp;Zone&amp;nbsp;Name&amp;nbsp;(ID)"&lt;/span&gt;,
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: green"&gt;"Local&amp;nbsp;Time&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;"&lt;/span&gt;,
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: green"&gt;"DST?"&lt;/span&gt;,
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: green"&gt;"Time&amp;nbsp;Zone&amp;nbsp;Information"&lt;/span&gt;);
&amp;nbsp;&amp;nbsp;&lt;span style="color: navy"&gt;Console&lt;/span&gt;&lt;span style="color: magenta"&gt;.&lt;/span&gt;WriteLine(&lt;span style="color: green;"&gt;"---------------------------+------------"&lt;/span&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: magenta"&gt;+&lt;/span&gt;&amp;nbsp;&lt;span style="color: green"&gt;"----------+---------------------------------------"&lt;/span&gt;);
 
&amp;nbsp;&amp;nbsp;&lt;span style="color: maroon"&gt;foreach&lt;/span&gt;&amp;nbsp;(&lt;span style="color: navy"&gt;String&lt;/span&gt;&amp;nbsp;tzID&amp;nbsp;&lt;span style="color: maroon;"&gt;in&lt;/span&gt;&amp;nbsp;zoneIDs)&amp;nbsp;{
 
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: navy"&gt;TimeZoneInfo&lt;/span&gt;&amp;nbsp;tzInfo&amp;nbsp;&lt;span style="color: magenta;"&gt;=&lt;/span&gt;&amp;nbsp;&lt;span style="color: navy"&gt;TimeZoneInfo&lt;/span&gt;&lt;span style="color: magenta;"&gt;.&lt;/span&gt;FindSystemTimeZoneById(tzID);
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: #2b91af"&gt;DateTime&lt;/span&gt;&amp;nbsp;tzTime&amp;nbsp;&lt;span style="color: magenta;"&gt;=&lt;/span&gt;&amp;nbsp;&lt;span style="color: navy"&gt;TimeZoneInfo&lt;/span&gt;&lt;span style="color: magenta;"&gt;.&lt;/span&gt;ConvertTime(utcTime,&amp;nbsp;tzInfo);
 
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;span style="color: navy"&gt;Console&lt;/span&gt;&lt;span style="color: magenta"&gt;.&lt;/span&gt;WriteLine(format,&amp;nbsp;tzID,
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;tzTime&lt;span style="color: magenta"&gt;.&lt;/span&gt;ToString(&lt;span style="color: green;"&gt;"yyyy-MM-dd&amp;nbsp;HH:mm"&lt;/span&gt;),
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;tzInfo&lt;span style="color: magenta"&gt;.&lt;/span&gt;IsDaylightSavingTime(tzTime)&amp;nbsp;&lt;span style="color: magenta;"&gt;?&lt;/span&gt;&amp;nbsp;&lt;span style="color: green"&gt;"DST&amp;nbsp;"&lt;/span&gt;&amp;nbsp;:&amp;nbsp;&lt;span style="color: green;"&gt;"&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;"&lt;/span&gt;,
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;tzInfo&lt;span style="color: magenta"&gt;.&lt;/span&gt;DisplayName);
&amp;nbsp;&amp;nbsp;}&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;
}
 
}&amp;nbsp;&amp;nbsp;&lt;span style="font-weight: 700;color: gray"&gt;//&amp;nbsp;public&amp;nbsp;static&amp;nbsp;class&amp;nbsp;ConfusingTimeZoneNames_Demo&lt;/span&gt;
}&amp;nbsp;&amp;nbsp;&lt;span style="font-weight: 700;color: gray"&gt;//&amp;nbsp;namespace&amp;nbsp;Microsoft.Misc.MSDNBlog&lt;/span&gt;
&lt;/pre&gt;
&lt;p&gt;&lt;a href="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-30-50-metablogapi/6327.image_5F00_346DD24A.png"&gt;&lt;img height="109" width="533" src="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-30-50-metablogapi/0363.image_5F00_thumb_5F00_6EB9225E.png" alt="image" border="0" title="image" style="background-image: none; border-right-width: 0px; margin: ; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;To summarise: Be careful when instantiating &lt;span style="font-family: Consolas;"&gt;TimeZoneInfo&lt;/span&gt; objects. Always double-check that the zone name you are using is the correct one, even if it appears obvious at first. And if your application behaves weirdly, double-check if you have possibly created the wrong TimeZoneInfo object due to a similarity in name IDs. For more information about time zones in various places around the world, check out &lt;a href="http://www.timeanddate.com/worldclock/full.html"&gt;http://www.timeanddate.com/worldclock/full.html&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;Enjoy!&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10074441" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/bclteam/archive/tags/Globalization/">Globalization</category><category domain="http://blogs.msdn.com/b/bclteam/archive/tags/Time+and+Calendar/">Time and Calendar</category></item><item><title>Optimizing Regular Expression Performance, Part II: Taking Charge of Backtracking [Ron Petrusha]</title><link>http://blogs.msdn.com/b/bclteam/archive/2010/08/03/optimizing-regular-expression-performance-part-ii-taking-charge-of-backtracking.aspx</link><pubDate>Tue, 03 Aug 2010 20:50:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10045582</guid><dc:creator>BCL Team</dc:creator><slash:comments>1</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/bclteam/rsscomments.aspx?WeblogPostID=10045582</wfw:commentRss><comments>http://blogs.msdn.com/b/bclteam/archive/2010/08/03/optimizing-regular-expression-performance-part-ii-taking-charge-of-backtracking.aspx#comments</comments><description>&lt;p&gt;One of the most powerful features of regular expressions in the .NET Framework -- and of Nondeterministic Finite Automaton (NFA) regular expression engines generally -- is their ability to execute in a non-linear manner. That is, instead of advancing one character at a time, they can return to a previous saved state in order to match a regular expression pattern. For example, if you try to match the string &amp;ldquo;A match.&amp;rdquo; with the regular expression pattern &lt;span style="color: #ff0000;"&gt;.+\.&lt;/span&gt; the regular expression engine first attempts to match the entire string. It then retreats one character so that the &lt;strong&gt;.+&lt;/strong&gt; construct matches &amp;ldquo;A match&amp;rdquo; and &lt;strong&gt;\.&lt;/strong&gt; matches the period at the end of the string. This ability to return to a previous saved state in order to continue the match is known as &lt;i&gt;backtracking&lt;/i&gt;.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Note&lt;/strong&gt;: This is the second part of a three-part series on optimizing regular expression performance. The first part, &lt;a href="http://blogs.msdn.com/b/bclteam/archive/2010/06/25/optimizing-regular-expression-performance-part-i-working-with-the-regex-class-and-regex-objects.aspx"&gt;Optimizing Regular Expression Performance, Part I: Working with the Regex Class and Regex Objects&lt;/a&gt;, discusses the efficient use of &lt;strong&gt;Regex&lt;/strong&gt; static and instance methods.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;Although backtracking contributes to the power and flexibility of regular expressions, it can have an enormous negative impact on performance. In a worst-case scenario, when backtracking is used excessively, it might take one or more days for the regular expression engine to process even a relatively short input string that does not match the regular expression pattern.&lt;/p&gt;
&lt;p&gt;The NFA Engine places control over backtracking (and therefore responsibility for the consequences of backtracking) in the hands of regular expression developers who may be unaware of how backtracking affects performance. This fact often goes overlooked both when creating regular expressions and when assessing regular expression performance. As a result, the inappropriate use of backtracking is one of the fundamental performance bottlenecks that applications relying on regular expressions encounter.&lt;/p&gt;
&lt;p&gt;Backtracking occurs when a regular expression contains the following language constructs and under the following conditions: &lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;An alternation construct, if the first alternative does not provide a successful pattern match. &lt;/li&gt;
&lt;li&gt;An indeterminate quantifier (such as &lt;strong&gt;*&lt;/strong&gt; or &lt;strong&gt;+&lt;/strong&gt;), when the greedy match resulting from the expression to which the quantifier is applied prevents a successful match. &lt;/li&gt;
&lt;li&gt;A conditional expression, if the first condition does not provide a successful pattern match. &lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;When the regular expression engine encounters one of these constructs or expressions, it saves its current state so that it can return to it if necessary.&lt;/p&gt;
&lt;p&gt;We&amp;rsquo;ll first examine backtracking with alternation, and then examine backtracking with nested quantifiers. We&amp;rsquo;ll finish by looking at a worst case scenario in which a poor use of backtracking causes execution time to increase exponentially as the number of characters in the string to be matched increases. In each case, we&amp;rsquo;ll attempt to show that an alternative pattern that better controls backtracking offers superior performance.&lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Note:&lt;/strong&gt; In the code examples in this article, we make extensive use of the &lt;strong&gt;System.Diagnostics.Stopwatch&lt;/strong&gt; class to measure regular expression performance. These measurements are used only for comparative purposes, and reflect performance on a particular system. They are not intended to be construed as benchmarks.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;h2&gt;Alternation and Backtracking&lt;/h2&gt;
&lt;p&gt;The alternation construct (&lt;strong&gt;|&lt;/strong&gt;) allows a regular expression pattern to include the equivalent of an &lt;strong&gt;Or&lt;/strong&gt; operator; the regular expression engine will match text that conforms to one of two or more patterns. The regular expression engine performs no optimization on alternation constructs.&lt;/p&gt;
&lt;p&gt;Because alternation is a backtracking construct, it can entail a significant performance penalty if the alternation pattern is not well crafted. In this section, we&amp;rsquo;ll examine some of the factors to consider when constructing an alternation pattern that will perform efficiently.&lt;/p&gt;
&lt;h3&gt;Order Matters&lt;/h3&gt;
&lt;p&gt;Alternation constructs are evaluated sequentially from left to right. The second alternative is evaluated only if the first alternative fails. If there are three or more alternatives, the third alternative is evaluated only if the first and second alternatives fail, and so on. Because of this, the ordering of items in an alternation construct is significant. Subpatterns that are more likely to be encountered in an input string should precede subpatterns that are less likely to be encountered.&lt;/p&gt;
&lt;p&gt;The following example uses an alternation construct to find words followed by one of a number of punctuation symbols in the text of Theodore Dreiser&amp;rsquo;s &lt;i&gt;The Financier&lt;/i&gt;. In the first regular expression pattern, punctuation symbols that are less likely to be encountered precede symbols that are more frequently encountered. In the second, punctuation symbols that are more likely to be encountered precede symbols that are less frequently encountered. &lt;/p&gt;
&lt;pre class="code"&gt;[Visual Basic]
Option Strict On

Imports System.Diagnostics
Imports System.IO
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      ' Organize the punctuation marks in a poor order.
      Dim pattern1 As String = "\b\w+(;|:|!|\?|\.|,)\s"
      Dim rgx1 As New Regex(pattern1, RegexOptions.SingleLine)
      Dim sw As Stopwatch
      Dim sr As New StreamReader(".\Dreiser_TheFinancier.txt")
      Dim input As String = sr.ReadToEnd()
      sr.Close()

      sw = Stopwatch.StartNew()
      Dim match1 As Match = rgx1.Match(input)
      Dim ctr1 As Integer
      Do While match1.Success
         ctr1 += 1
         match1 = match1.NextMatch
      Loop
      sw.Stop()
      Console.WriteLine("Found {0} matches in {1}", ctr1, sw.Elapsed)

      ' Organize the punctuation marks in rough order of occurrence.
      Dim pattern2 As String = "\b\w+(\.|,|\?|;|:|!)\s"
      Dim rgx2 As New Regex(pattern2, RegexOptions.SingleLine)

      sw = Stopwatch.StartNew()
      Dim match2 As Match = rgx2.Match(input)
      Dim ctr2 As Integer
      Do While match2.Success
         ctr2 += 1
         match2 = match2.NextMatch
      Loop
      sw.Stop()
      Console.WriteLine("Found {0} matches in {1}", ctr2, sw.Elapsed)
   End Sub
End Module
&lt;span style="font-family: Calibri;"&gt;&lt;/span&gt;&lt;/pre&gt;
&lt;pre class="code"&gt;[C#]
using System;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      // Organize the punctuation marks in a poor order.
      string pattern1 = @"\b\w+(;|:|!|\?|\.|,)\s";
      Regex rgx1 = new Regex(pattern1, RegexOptions.Singleline);
      Stopwatch sw;
      StreamReader sr = new StreamReader(@".\Dreiser_TheFinancier.txt");
      string input = sr.ReadToEnd();
      sr.Close();

      sw = Stopwatch.StartNew();
      Match match1 = rgx1.Match(input);
      int ctr1 = 0;
      while (match1.Success)
      {
         ctr1++;
         match1 = match1.NextMatch();
      }
      sw.Stop();
      Console.WriteLine("Found {0} matches in {1}", ctr1, sw.Elapsed);

      // Organize the punctuation marks in rough order of occurrence.
      string pattern2 = @"\b\w+(\.|,|\?|;|:|!)\s";
      Regex rgx2 = new Regex(pattern2, RegexOptions.Singleline);

      sw = Stopwatch.StartNew();
      Match match2 = rgx2.Match(input);
      int ctr2 = 0;
      while (match2.Success)
      {
         ctr2++;
         match2 = match2.NextMatch();
      }
      sw.Stop();
      Console.WriteLine("Found {0} matches in {1}", ctr2, sw.Elapsed);
   }
}&lt;/pre&gt;
&lt;p&gt;Output from the example shows that there is a small performance benefit from ordering the alternatives based on how likely they are to be encountered in the input string. The performance improvement is approximately 6% for this very simple regular expression, as the following graph shows. In a more complex regular expression pattern, particularly if he alternation pattern is followed by additional backtracking constructs, the performance benefit is likely to be much greater.&lt;/p&gt;
&lt;pre class="code"&gt;Found 26930 matches in 00:00:00.9649407
Found 26930 matches in 00:00:00.9044185
&lt;a href="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-30-50-metablogapi/8080.clip_5F00_image0024_5F00_30A30B21.gif"&gt;&lt;img height="344" width="582" src="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-30-50-metablogapi/6758.clip_5F00_image0024_5F00_thumb_5F00_0ED73290.gif" alt="clip_image002[4]" border="0" title="clip_image002[4]" style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" /&gt;&lt;/a&gt;&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h3&gt;Optimization Matters&lt;/h3&gt;
&lt;p&gt;Because alternation constructs involve backtracking, optimization is critical. Alternation patterns that are poorly written and that include duplicate elements perform much more poorly than those that do not. In the following example, the regular expression \b(the|this|that|then|there|these|those)\b matches a number of words starting with &amp;ldquo;th&amp;rdquo; (the, this, that, then, there, these, those) in a string. Because of backtracking, the regular expression engine performs the following steps to match the substring &amp;ldquo;these&amp;rdquo; in the input string:&lt;/p&gt;
&lt;table cellpadding="0" cellspacing="0" border="1"&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td width="55" valign="top"&gt;
&lt;p&gt;1&lt;/p&gt;
&lt;/td&gt;
&lt;td width="535" valign="top"&gt;
&lt;p&gt;It determines that the current position in the input string is on a word boundary. Because a grouping and alternation construct follow, it saves this position in the input string.&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td width="55" valign="top"&gt;
&lt;p&gt;2&lt;/p&gt;
&lt;/td&gt;
&lt;td width="535" valign="top"&gt;
&lt;p&gt;It begins comparing the &amp;ldquo;the&amp;rdquo; alternative with the input string. It compares &amp;ldquo;t&amp;rdquo; in the regular expression pattern with &amp;ldquo;t&amp;rdquo; in the input string and finds a match.&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td width="55" valign="top"&gt;
&lt;p&gt;3&lt;/p&gt;
&lt;/td&gt;
&lt;td width="535" valign="top"&gt;
&lt;p&gt;It compares &amp;ldquo;h&amp;rdquo; in the regular expression pattern with &amp;ldquo;h&amp;rdquo; in the input string and finds a match.&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td width="55" valign="top"&gt;
&lt;p&gt;4&lt;/p&gt;
&lt;/td&gt;
&lt;td width="535" valign="top"&gt;
&lt;p&gt;It compares &amp;ldquo;e&amp;rdquo; in the regular expression pattern with &amp;ldquo;e&amp;rdquo; in the input string and finds a match.&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td width="55" valign="top"&gt;
&lt;p&gt;5&lt;/p&gt;
&lt;/td&gt;
&lt;td width="535" valign="top"&gt;
&lt;p&gt;It determines whether the current position in the input string is on a word boundary. Because it is in the middle of the substring &amp;ldquo;these&amp;rdquo;, the match with the first alternation pattern fails, and the regular expression engine returns to its saved position (the beginning of the substring &amp;ldquo;these&amp;rdquo;) in the input string.&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td width="55" valign="top"&gt;
&lt;p&gt;6-8&lt;/p&gt;
&lt;/td&gt;
&lt;td width="535" valign="top"&gt;
&lt;p&gt;It compares the &amp;ldquo;this&amp;rdquo; alternative with the input string. It matches &amp;ldquo;t&amp;rdquo; and &amp;ldquo;h&amp;rdquo;, but fails to match &amp;ldquo;i" with &amp;ldquo;e&amp;rdquo; in the input string. The regular expression engine returns to its saved position in the input string.&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td width="55" valign="top"&gt;
&lt;p&gt;9-11&lt;/p&gt;
&lt;/td&gt;
&lt;td width="535" valign="top"&gt;
&lt;p&gt;It compares the &amp;ldquo;that&amp;rdquo; alternative with the input string. It matches &amp;ldquo;t&amp;rdquo; and &amp;ldquo;h&amp;rdquo;, but fails to match &amp;ldquo;a" with &amp;ldquo;e&amp;rdquo; in the input string. The regular expression engine returns to its saved position in the input string.&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td width="55" valign="top"&gt;
&lt;p&gt;12-15&lt;/p&gt;
&lt;/td&gt;
&lt;td width="535" valign="top"&gt;
&lt;p&gt;It compares the &amp;ldquo;then&amp;rdquo; alternative with the input string. It matches &amp;ldquo;t&amp;rdquo;, &amp;ldquo;h&amp;rdquo;, and &amp;ldquo;e&amp;rdquo;, but fails to match &amp;ldquo;n" with &amp;ldquo;s&amp;rdquo; in the input string. The regular expression engine returns to its saved position in the input string.&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td width="55" valign="top"&gt;
&lt;p&gt;16-19&lt;/p&gt;
&lt;/td&gt;
&lt;td width="535" valign="top"&gt;
&lt;p&gt;It compares the &amp;ldquo;there&amp;rdquo; alternative with the input string. It matches &amp;ldquo;t&amp;rdquo;, &amp;ldquo;h&amp;rdquo;, and &amp;ldquo;e&amp;rdquo;, but fails to match &amp;ldquo;r" with &amp;ldquo;s&amp;rdquo; in the input string. The regular expression engine returns to its saved position in the input string.&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td width="55" valign="top"&gt;
&lt;p&gt;20-25&lt;/p&gt;
&lt;/td&gt;
&lt;td width="535" valign="top"&gt;
&lt;p&gt;It compares the &amp;ldquo;these&amp;rdquo; alternative with the input string. It matches &amp;ldquo;t&amp;rdquo;, &amp;ldquo;h&amp;rdquo;, &amp;ldquo;e&amp;rdquo;, &amp;ldquo;s&amp;rdquo;, and &amp;ldquo;e&amp;rdquo;. It then determines that the current position in the input string is on a word boundary. The match succeeds. The last alternative in the regular expression (those) is not tested.&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;By using alternation only for unique portions of the regular expression pattern, we can improve the efficiency of string comparisons. In our example, because the substring &amp;ldquo;th&amp;rdquo; is common to all alternation patterns, we can rewrite the regular expression pattern as follows: &lt;/p&gt;
&lt;p&gt;\bth(e|is|at|en|ere|ese|ose)\b&lt;/p&gt;
&lt;p&gt;Since individual alternatives still share characters in common, we can further optimize this regular expression pattern through grouping:&lt;/p&gt;
&lt;p&gt;\bth(e(n|re|se)|at|is|ose)\b&lt;/p&gt;
&lt;p&gt;While 25 comparisons were required to match the input string &amp;ldquo;these&amp;rdquo; with the regular expression pattern &lt;span style="color: #ff0000;"&gt;\b(the|this|that|then|there|these|those)\b&lt;/span&gt; , only 9 comparisons are required to match it with &lt;span style="color: #ff0000;"&gt;\bth(e(n|re|se)|at|is|ose)\b&lt;/span&gt;. The following table lists the comparisons that the regular expression engine makes to match the input string &amp;ldquo;these&amp;rdquo; with this last regular expression pattern.&lt;/p&gt;
&lt;table cellpadding="0" cellspacing="0" border="1"&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td width="55" valign="top"&gt;
&lt;p&gt;1&lt;/p&gt;
&lt;/td&gt;
&lt;td width="535" valign="top"&gt;
&lt;p&gt;It determines that the current position in the input string is on a word boundary. &lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td width="55" valign="top"&gt;
&lt;p&gt;2&lt;/p&gt;
&lt;/td&gt;
&lt;td width="535" valign="top"&gt;
&lt;p&gt;It matches &amp;ldquo;t&amp;rdquo; in the pattern with &amp;ldquo;t&amp;rdquo; in the input string.&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td width="55" valign="top"&gt;
&lt;p&gt;3&lt;/p&gt;
&lt;/td&gt;
&lt;td width="535" valign="top"&gt;
&lt;p&gt;It matches &amp;ldquo;h&amp;rdquo; in the pattern with &amp;ldquo;h&amp;rdquo; in the input string. Because a grouping and alternation construct follows, it saves this position in the input string.&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td width="55" valign="top"&gt;
&lt;p&gt;4&lt;/p&gt;
&lt;/td&gt;
&lt;td width="535" valign="top"&gt;
&lt;p&gt;It matches &amp;ldquo;e&amp;rdquo; in the pattern with &amp;ldquo;e&amp;rdquo; in the input string. Because a grouping and alternation construct follows, it saves this position (the second saved position) in the input string.&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td width="55" valign="top"&gt;
&lt;p&gt;5&lt;/p&gt;
&lt;/td&gt;
&lt;td width="535" valign="top"&gt;
&lt;p&gt;It attempts to match &amp;ldquo;n&amp;rdquo; in the pattern with &amp;ldquo;s&amp;rdquo; in the input string. The match fails, and the regular expression engine returns to its second saved position in the input string.&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td width="55" valign="top"&gt;
&lt;p&gt;6&lt;/p&gt;
&lt;/td&gt;
&lt;td width="535" valign="top"&gt;
&lt;p&gt;It attempts to match &amp;ldquo;r&amp;rdquo; in the pattern with &amp;ldquo;s&amp;rdquo; in the input string. The match fails, and the regular expression engine returns to its second saved position in the input string. Note that it does not test the &amp;ldquo;e&amp;rdquo; because it failed to match &amp;ldquo;r&amp;rdquo;.&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td width="55" valign="top"&gt;
&lt;p&gt;7-8&lt;/p&gt;
&lt;/td&gt;
&lt;td width="535" valign="top"&gt;
&lt;p&gt;It attempts to match &amp;ldquo;se&amp;rdquo; in the pattern with &amp;ldquo;se&amp;rdquo; in the input string. The match succeeds.&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td width="55" valign="top"&gt;
&lt;p&gt;9&lt;/p&gt;
&lt;/td&gt;
&lt;td width="535" valign="top"&gt;
&lt;p&gt;It determines that the current position in the input string is on a word boundary. The match succeeds.&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;The following is the complete example. &lt;/p&gt;
&lt;pre class="code"&gt;[Visual Basic]
Option Strict On

Imports System.Diagnostics
Imports System.IO
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim sw As Stopwatch
      Dim sr As New StreamReader(".\Dreiser_TheFinancier.txt")
      Dim input As String = sr.ReadToEnd()
      sr.Close()
      Dim ctr As Integer

      sw = Stopwatch.StartNew()
      ctr = 0
      Dim unoptPattern As String = "\b(the|this|that|then|there|these|those)\b"
      Dim rgxUnopt As New Regex(unoptPattern, RegexOptions.IgnoreCase)
      Dim match1 As Match = rgxUnopt.Match(input)
      Do While match1.Success
         ctr += 1
         match1 = match1.NextMatch()
      Loop
      sw.Stop()
      Console.WriteLine("{0}:{3}   Found {1:N0} matches in {2}", 
                        unoptPattern, ctr, sw.Elapsed, vbCrLf)
      Console.WriteLine()

      sw = Stopwatch.StartNew()
      ctr = 0
      Dim optPattern As String = "\bth(e(n|re|se)|at|is|ose)\b"
      Dim rgxOpt As New Regex(unoptPattern, RegexOptions.IgnoreCase)
      Dim match2 As Match = rgxOpt.Match(input)
      Do While match2.Success
         ctr += 1
         match2 = match2.NextMatch()
      Loop
      sw.Stop()
      Console.WriteLine("{0}:{3}   Found {1:N0} matches in {2}", 
                        optPattern, ctr, sw.Elapsed, vbCrLf)
   End Sub
End Module&lt;/pre&gt;
&lt;pre class="code"&gt;[C#]
using System;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        Stopwatch sw;
        StreamReader sr = new StreamReader(@".\Dreiser_TheFinancier.txt");
        string input = sr.ReadToEnd();
        sr.Close();
        int ctr;

        sw = Stopwatch.StartNew();
        ctr = 0;
        string unoptPattern = @"\b(the|this|that|then|there|these|those)\b";
        Regex rgxUnopt = new Regex(unoptPattern, 
                                   RegexOptions.IgnoreCase);
        Match match1 = rgxUnopt.Match(input);
        while (match1.Success)
        {
            ctr++;
            match1 = match1.NextMatch();
        }
        sw.Stop();
        Console.WriteLine("{0}:\n   Found {1:N0} matches in {2}\n", 
                          unoptPattern, ctr, sw.Elapsed);

        sw = Stopwatch.StartNew();
        ctr = 0;
        string optPattern = @"\bth(e(n|re|se)|at|is|ose)\b";
        Regex rgxOpt = new Regex(unoptPattern,
                                 RegexOptions.IgnoreCase);
        Match match2 = rgxOpt.Match(input);
        while (match2.Success)
        {
            ctr++;
            match2 = match2.NextMatch();
        }
        sw.Stop();
        Console.WriteLine("{0}:\n   Found {1:N0} matches in {2}", 
                          optPattern, ctr, sw.Elapsed);
    }
}&lt;/pre&gt;
&lt;p&gt;The optimized regular expression offers approximately a 35% performance improvement over the unoptimized regular expression, as indicated by the following output and graph.&lt;/p&gt;
&lt;pre class="code"&gt;\b(the|this|that|then|there|these|those)\b:
   Found 13,459 matches in 00:00:00.1833098

\bth(e(n|re|se)|at|is|ose)\b:
   Found 13,459 matches in 00:00:00.1184890
&lt;a href="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-30-50-metablogapi/6266.clip_5F00_image0026_5F00_679CE95A.gif"&gt;&lt;img height="341" width="578" src="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-30-50-metablogapi/3527.clip_5F00_image0026_5F00_thumb_5F00_55542298.gif" alt="clip_image002[6]" border="0" title="clip_image002[6]" style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" /&gt;&lt;/a&gt;&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;h2&gt;Optional Quantifiers and Backtracking&lt;/h2&gt;
&lt;p&gt;The regular expression engine also uses backtracking whenever a subexpression includes an optional quantifier (such as &lt;strong&gt;*&lt;/strong&gt; or &lt;strong&gt;+&lt;/strong&gt;). For example, the regular expression pattern &lt;span style="color: #ff0000;"&gt;\b\p{Lu}\w*\b&lt;/span&gt; matches all words beginning with an uppercase character. To allow for the possibility that a word might consist of a single uppercase letter, the \w* subexpression matches any word character zero or more times. Because * is an optional quantifier, the regular expression engine saves its state with each word character matched, in case it has to abandon a portion of the match and return to a previous saved state in order to match the input string with a later portion of the regular expression pattern.&lt;/p&gt;
&lt;h3&gt;Is Backtracking Necessary?&lt;/h3&gt;
&lt;p&gt;An important question to ask about any regular expression that uses backtracking is whether, in view of its associated performance penalty, backtracking is necessary for a successful match. Backtracking often is necessary because regular expressions are greedy, and a greedy match of a subexpression is likely to consume some portion of what would otherwise be a successful match. But in many cases, backtracking is used unintentionally, because optional quantifiers that backtrack are more familiar and frequently used than their alternatives. However, backtracking comes at a price. Each time an optional quantifier is applied to an input string, the regular expression engine must save the state of the match at that point so that it can return to it if a later portion of the match fails. To put it another way, needless backtracking exacts a substantial performance penalty.&lt;/p&gt;
&lt;p&gt;Let&amp;rsquo;s return to our example regular expression pattern, \b\p{Lu}\w*\b. Because a word boundary is not the same as, or a subset of, a word character, there is no possibility that the regular expression engine will cross a word boundary when matching word characters. This means that for this regular expression, backtracking can never contribute to the overall success of any match -- it can only extract a performance penalty, because the regular expression engine is forced to save its state for each successful preliminary match of a word character. &lt;/p&gt;
&lt;p&gt;In cases where backtracking is unnecessary, it can be disabled by using the &lt;strong&gt;(?&amp;gt;&lt;i&gt;subexpression&lt;/i&gt;)&lt;/strong&gt; language construct, where &lt;i&gt;subexpression&lt;/i&gt; is the regular expression subpattern that should not backtrack. To disable backtracking, we can change our regular expression from &lt;span style="color: #ff0000;"&gt;\b\p{Lu}\w*\b&lt;/span&gt; to &lt;span style="color: #ff0000;"&gt;\b\p{Lu}(?&amp;gt;\w*)\b&lt;/span&gt;. The following example uses these two regular expressions to extract words from the text of Theodore Dreisier&amp;rsquo;s &lt;i&gt;The Financier&lt;/i&gt;.&lt;/p&gt;
&lt;pre class="code"&gt;[Visual Basic]
Imports System.Diagnostics
Imports System.IO
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim sw As Stopwatch
      Dim sr As New StreamReader(".\Dreiser_TheFinancier.txt")
      Dim input As String = sr.ReadToEnd()
      sr.Close()
      Dim ctr As Integer

      sw = Stopwatch.StartNew()
      ctr = 0
      Dim backtrackingPattern As String = "\b\p{Lu}\w*\b"
      Dim backtrackingRegex As New Regex(backtrackingPattern)
      Dim match1 As Match = backtrackingRegex.Match(input)
      Do While match1.Success
         ctr += 1
         match1 = match1.NextMatch()
      Loop
      sw.Stop()
      Console.WriteLine("{0}:\n   Found {1:N0} matches in {2}\n", 
                        backtrackingPattern, ctr, sw.Elapsed)

      sw = Stopwatch.StartNew()
      ctr = 0
      Dim noBacktrackPattern As String = "\b\p{Lu}(?&amp;gt;\w*)\b"
      Dim nonBacktrackingRegex As New Regex(noBacktrackPattern)
      Dim match2 As Match = nonBacktrackingRegex.Match(input)
      Do While match2.Success
         ctr += 1
         match2 = match2.NextMatch()
      Loop
      sw.Stop()
      Console.WriteLine("{0}:\n   Found {1:N0} matches in {2}", 
                        noBacktrackPattern, ctr, sw.Elapsed)
   End Sub
End Module&lt;/pre&gt;
&lt;pre class="code"&gt;[C#]
using System;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        Stopwatch sw;
        StreamReader sr = new StreamReader(@".\Dreiser_TheFinancier.txt");
        string input = sr.ReadToEnd();
        sr.Close();
        int ctr;

        sw = Stopwatch.StartNew();
        ctr = 0;
        string backtrackingPattern = @"\b\p{Lu}\w*\b";
        Regex backtrackingRegex = new Regex(backtrackingPattern);
        Match match1 = backtrackingRegex.Match(input);
        while (match1.Success)
        {
            ctr++;
            match1 = match1.NextMatch();
        }
        sw.Stop();
        Console.WriteLine("{0}:\n   Found {1:N0} matches in {2}\n",
                          backtrackingPattern, ctr, sw.Elapsed);
        sw = Stopwatch.StartNew();
        ctr = 0;
        string noBacktrackPattern = @"\b\p{Lu}(?&amp;gt;\w*)\b";
        Regex nonBacktrackingRegex = new Regex(noBacktrackPattern);
        Match match2 = nonBacktrackingRegex.Match(input);
        while (match2.Success)
        {
            ctr++;
            match2 = match2.NextMatch();
        }
        sw.Stop();
        Console.WriteLine("{0}:\n   Found {1:N0} matches in {2}",
                          noBacktrackPattern, ctr, sw.Elapsed);
    }
}&lt;/pre&gt;
&lt;p&gt;Because it does not have to keep track of previous saved states, the regular expression that explicitly disables backtracking executes approximately 40% faster than the one that uses unnecessary backtracking. The following output from this example and graph illustrate the difference in performance.&lt;/p&gt;
&lt;pre class="code"&gt;\b\p{Lu}\w*\b:
   Found 24,157 matches in 00:00:00.2465120

\b\p{Lu}(?&amp;gt;\w)*\b:
   Found 24,157 matches in 00:00:00.1483269&lt;/pre&gt;
&lt;pre class="code"&gt;&lt;a href="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-30-50-metablogapi/7725.clip_5F00_image0028_5F00_394363AD.gif"&gt;&lt;img height="341" width="578" src="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-30-50-metablogapi/6761.clip_5F00_image0028_5F00_thumb_5F00_6DE3BFE8.gif" alt="clip_image002[8]" border="0" title="clip_image002[8]" style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" /&gt;&lt;/a&gt;&lt;/pre&gt;
&lt;p&gt;
Note that disabling backtracking is not always an option, since it changes the behavior of the regular expression engine. In the following example, the regular expression pattern &lt;span style="color: #ff0000;"&gt;(a+)ab&lt;/span&gt; matches one or more &amp;ldquo;a&amp;rdquo; characters, followed by the substring &amp;ldquo;ab&amp;rdquo;. This pattern matches the input string &amp;ldquo;aaaaaaaab&amp;rdquo;. However, if we change the regular expression pattern to &lt;span style="color: #ff0000;"&gt;(?&amp;gt;a+)ab&lt;/span&gt; to disable backtracking, the input string no longer matches. This is because when backtracking disabled, the regular expression engine is greedy and will not give up the last matched &amp;ldquo;a&amp;rdquo; in the string so that the match with &amp;ldquo;ab&amp;rdquo; succeeds. 
&lt;/p&gt;
&lt;pre class="code"&gt;[Visual Basic]
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim input As String = "aaaaaaaab"
      
      Dim backtrackingPattern As String = "(a+)ab"
      Console.WriteLine(Regex.IsMatch(input, backtrackingPattern))
      ' Displays True.
      
      Dim nonBacktrackingPattern As String = "(?&amp;gt;a+)ab"
      Console.WriteLine(Regex.IsMatch(input, nonBacktrackingPattern))
      ' Displays False.          
   End Sub
End Module&lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;pre class="code"&gt;[C#]
using System;
using System.Text.RegularExpressions;
 
public class Example
{
   public static void Main()
   {
      string input = "aaaaaaaab";
      
      string backtrackingPattern = "(a+)ab";
      Console.WriteLine(Regex.IsMatch(input, backtrackingPattern));
      // Displays True.
      
      string nonBacktrackingPattern = "(?&amp;gt;a+)ab";
      Console.WriteLine(Regex.IsMatch(input, nonBacktrackingPattern));
      // Displays False.          
   }
}&lt;/pre&gt;
&lt;h3&gt;Nested Optional Quantifiers and Backtracking&lt;/h3&gt;
&lt;p&gt;When developing regular expressions, developers typically focus on creating patterns that will match particular input. They rarely focus on creating patterns that will efficiently handle input that does not match the pattern. Frequently, this is justified. For example, if a regular expression is designed to extract substrings from text that follows a known format, there is no need to focus on non-matches. However, the regular expression engine can exhibit some of its poorest performance when handling text that does not conform to a specific regular expression pattern. In particular, this occurs when a regular expression that uses nested optional quantifiers (and therefore relies on extensive backtracking) is used to process text that does not conform to the pattern.&lt;/p&gt;
&lt;p&gt;For example, in an order processing system, let&amp;rsquo;s say a regular expression is used to ensure that an item identifier conforms to a standard pattern. All item identifiers must contain at least one alphanumeric character; if they have multiple characters, the second to last character must also be alphanumeric; and the last character must be a dollar sign (&amp;ldquo;$&amp;rdquo;). Any intermediate characters must be word characters (that is, alphanumeric characters or underscores), periods, or hyphens. The regular expression pattern that was developed to reflect the format of the item identifier is &lt;span style="color: #ff0000;"&gt;^[0-9A-Z]([-.\w]*[0-9A-Z])*\$$&lt;/span&gt;. A new employee who is being trained to do data entry enters one item identifier correctly, but then enters # instead of $ as the ending symbol for the next item. The following code illustrates this regular expression pattern and the data entry input. As the output shows, the regular expression performs efficiently when it is able to match the input identifier, but performance degrades drastically if it encounters an identifier that does not match the pattern.&lt;/p&gt;
&lt;pre class="code"&gt;[Visual Basic]
Imports System.Diagnostics
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim pattern As String = "^[0-9A-Z]([-.\w]*[0-9A-Z])*\$$"
      Dim rgx As New Regex(pattern, RegexOptions.IgnoreCase)
      Dim sw As Stopwatch

      Dim items() As String = { "A163.1523C$", 
                                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa#" }
      Dim toValidate, result As String
      
      For Each item In items
         For ctr As Integer = 1 To item.Length
            toValidate = item.Substring(0, ctr)     
            sw = Stopwatch.StartNew() 
   
            If rgx.IsMatch(toValidate) Then
               result = "Match"
            Else
               result = "No match"
            End If
            sw.Stop()
            Console.WriteLine("{0} with {1} characters in {2}", result, ctr, 
                              sw.Elapsed)   
         Next
         Console.WriteLine()               
      Next
   End Sub
End Module &lt;/pre&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;pre class="code"&gt;[C#]
using System;
using System.Diagnostics;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern = @"^[0-9A-Z]([-.\w]*[0-9A-Z])*\$$";
      Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);
      Stopwatch sw;

      string[] items= { "A163.1523C$", 
                        "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa#" };
      string toValidate, result;
      
      foreach (var item in items) {
         for (int ctr = 1; ctr &amp;lt;= item.Length; ctr++) {
            toValidate = item.Substring(0, ctr);     
            sw = Stopwatch.StartNew(); 
   
            if (rgx.IsMatch(toValidate))
               result = "Match";
            else
               result = "No match";

            sw.Stop();
            Console.WriteLine("{0} with {1} characters in {2}", result, ctr, 
                              sw.Elapsed);   
         }
         Console.WriteLine();               
      }
   }
}&lt;/pre&gt;
&lt;p&gt;The example displays the following output:&lt;/p&gt;
&lt;pre class="code"&gt;No match with 1 characters in 00:00:00.0000252
No match with 2 characters in 00:00:00.0000132
No match with 3 characters in 00:00:00.0000048
No match with 4 characters in 00:00:00.0000061
No match with 5 characters in 00:00:00.0000071
No match with 6 characters in 00:00:00.0000259
No match with 7 characters in 00:00:00.0000175
No match with 8 characters in 00:00:00.0000307
No match with 9 characters in 00:00:00.0000573
No match with 10 characters in 00:00:00.0001128
Match with 11 characters in 00:00:00.0000035

No match with 1 characters in 00:00:00.0000016
No match with 2 characters in 00:00:00.0000022
No match with 3 characters in 00:00:00.0000029
No match with 4 characters in 00:00:00.0000045
No match with 5 characters in 00:00:00.0000081
No match with 6 characters in 00:00:00.0000145
No match with 7 characters in 00:00:00.0000265
No match with 8 characters in 00:00:00.0000521
No match with 9 characters in 00:00:00.0001017
No match with 10 characters in 00:00:00.0002032
No match with 11 characters in 00:00:00.0004016
No match with 12 characters in 00:00:00.0007994
No match with 13 characters in 00:00:00.0015952
No match with 14 characters in 00:00:00.0032086
No match with 15 characters in 00:00:00.0065094
No match with 16 characters in 00:00:00.0129808
No match with 17 characters in 00:00:00.0270169
No match with 18 characters in 00:00:00.0553021
No match with 19 characters in 00:00:00.1070363
No match with 20 characters in 00:00:00.2208385
No match with 21 characters in 00:00:00.4289808
No match with 22 characters in 00:00:00.8553915
No match with 23 characters in 00:00:01.6993887
No match with 24 characters in 00:00:03.3938261
No match with 25 characters in 00:00:06.8359716
No match with 26 characters in 00:00:13.5125933
No match with 27 characters in 00:00:27.2257724
No match with 28 characters in 00:00:53.8205646
No match with 29 characters in 00:01:49.2090587
No match with 30 characters in 00:03:35.8028235
No match with 31 characters in 00:07:11.6145706
No match with 32 characters in 00:10:46.0044969&lt;/pre&gt;
&lt;p&gt;This example evaluates the performance of the regular expression engine based on the number of characters passed to it in the input string. As the following chart shows, for an input string that does not match the regular expression pattern, execution time approximately doubles each time another character is added to the string. It takes slightly over 10 minutes for the regular expression engine to recognize that an input string consisting of 32 characters does not match the regular expression pattern. Expanding the input to 35 characters would take approximately 1 hour and 20 minutes. Processing a string with 38 characters would take over 10 hours. Processing a string with 40 characters would take nearly two days. Visually scanning the string would be significantly faster.&lt;/p&gt;
&lt;p&gt;&lt;a href="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-30-50-metablogapi/3122.clip_5F00_image00210_5F00_7496C96B.gif"&gt;&lt;img height="347" width="567" src="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-30-50-metablogapi/6758.clip_5F00_image00210_5F00_thumb_5F00_3460AFF1.gif" alt="clip_image002[10]" border="0" title="clip_image002[10]" style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" /&gt;&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;This atrociously poor performance is tied to the behavior of the NFA regular expression engine in the .NET Framework. When the regular expression engine cannot find a match and the pattern requires backtracking, the engine must exhaust all possible paths through the data before it can conclude that a match has failed; so an unsuccessful match always represents a worst-case scenario. (For more information on the NFA engine and backtracking, see &lt;a href="http://msdn.microsoft.com/en-us/library/e347654k.aspx"&gt;Details of Regular Expression Behavior&lt;/a&gt; and &lt;a href="http://msdn.microsoft.com/en-us/library/dsy130b4.aspx"&gt;Backtracking&lt;/a&gt; in the MSDN Library.) Because of the nested quantifiers in our example, the number of possible matches that the regular expression engine has to examine before concluding that a match has failed increases exponentially with each character after the first character in the input string.&lt;/p&gt;
&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;Not all nested quantifiers impact performance in this way. In our example, the real problem in the subexpression &lt;span style="color: #ff0000;"&gt;([-.\w]*[0-9A-Z])*&lt;/span&gt; is that the last character to be matched (any numeric character from 0 to 9, or any alphanumeric character from A to Z) is a subset of the previous subexpression (any word character &amp;ndash; that is, any numeric or alphanumeric character or an underscore -- along with a hyphen and a period). A partially successful match makes it difficult for the regular expression engine to determine whether a particular character belongs to the first subexpression, the ending character of the expression, or to a repetition of the first subexpression or the ending character. The inability to successfully match the entire regular expression results in excessive backtracking, so that the number of possible paths through the input string increases exponentially with each character that can be matched. (For a description of the additional comparisons performed by the regular expression engine when backtracking, see the &amp;ldquo;Backtracking with Nested Optional Quantifiers&amp;rdquo; section in the &lt;a href="http://msdn.microsoft.com/en-us/library/dsy130b4.aspx"&gt;Backtracking&lt;/a&gt; topic in the MSDN Library.)&lt;/p&gt;
&lt;p&gt;In cases where excessive backtracking causes performance problems, other language constructs can often be used in place of the nested quantifiers. In many cases, nested quantifiers can be replaced by a single quantifier and zero-width lookbehind or lookahead assertion. Zero-width assertions do not advance the position counter in the input string. They either look ahead of or immediately behind the current position to determine whether the pattern defined by the assertion is true. If it is not, the match fails. (For information on positive lookahead and positive lookbehind, see &lt;a href="http://msdn.microsoft.com/en-us/library/bs2twtah.aspx"&gt;Grouping Constructs&lt;/a&gt; in the MSDN documentation.) For example, we can replace our previous regular expression to validate an item identifier with &lt;span style="color: #ff0000;"&gt;^[0-9A-Z][-.\w]*(?&amp;lt;=[0-9A-Z])\$&lt;/span&gt;, which uses positive lookbehind when the $ symbol is matched to ensure that the character before $ is either numeric or alphanumeric. This regular expression is interpreted as follows: &lt;/p&gt;
&lt;table style="width: 415px;" cellpadding="0" cellspacing="0" border="1"&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td width="115" valign="top"&gt;
&lt;p&gt;&lt;strong&gt;Pattern &lt;/strong&gt;&lt;/p&gt;
&lt;/td&gt;
&lt;td width="298" valign="top"&gt;
&lt;p&gt;&lt;strong&gt;Description&lt;/strong&gt;&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td width="115" valign="top"&gt;
&lt;p&gt;^&lt;/p&gt;
&lt;/td&gt;
&lt;td width="298" valign="top"&gt;
&lt;p&gt;Begin the match at the beginning of the string.&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td width="115" valign="top"&gt;
&lt;p&gt;[0-9A-Z]&lt;/p&gt;
&lt;/td&gt;
&lt;td width="298" valign="top"&gt;
&lt;p&gt;Match any numeric (0-9) or alphanumeric (A-Z) character.The comparison is not case-sensitive.&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td width="115" valign="top"&gt;
&lt;p&gt;[-.\w]*&lt;/p&gt;
&lt;/td&gt;
&lt;td width="298" valign="top"&gt;
&lt;p&gt;Match zero or more word, hyphen, or period characters.&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td width="115" valign="top"&gt;
&lt;p&gt;\$&lt;/p&gt;
&lt;/td&gt;
&lt;td width="298" valign="top"&gt;
&lt;p&gt;Match the $ character.&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td width="115" valign="top"&gt;
&lt;p&gt;(?&amp;lt;=[0-9A-Z])&lt;/p&gt;
&lt;/td&gt;
&lt;td width="298" valign="top"&gt;
&lt;p&gt;Determine whether the character before the current character is numeric (0-9) or alphanumeric (A-Z).The comparison is not case sensitive. This is a zero-width assertion; it does not cause the position counter in the input string to advance.&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;This produces the following output:&lt;/p&gt;
&lt;pre class="code"&gt;No match with 1 characters in 00:00:00.0498953
No match with 2 characters in 00:00:00.0002162
No match with 3 characters in 00:00:00.0000237
No match with 4 characters in 00:00:00.0000333
No match with 5 characters in 00:00:00.0000596
Match with 6 characters in 00:00:00.0000500
Match with 7 characters in 00:00:00.0000256
Match with 8 characters in 00:00:00.0000237
Match with 9 characters in 00:00:00.0000198
Match with 10 characters in 00:00:00.0000198
Match with 11 characters in 00:00:00.0000186
Match with 12 characters in 00:00:00.0000192
Match with 13 characters in 00:00:00.0000494
Match with 14 characters in 00:00:00.0000449

No match with 1 characters in 00:00:00.0000288
No match with 2 characters in 00:00:00.0000205
No match with 3 characters in 00:00:00.0000205
No match with 4 characters in 00:00:00.0000301
No match with 5 characters in 00:00:00.0000481
No match with 6 characters in 00:00:00.0000269
No match with 7 characters in 00:00:00.0000218
No match with 8 characters in 00:00:00.0000346
No match with 9 characters in 00:00:00.0000468
No match with 10 characters in 00:00:00.0000442
No match with 11 characters in 00:00:00.0000346
No match with 12 characters in 00:00:00.0000891
No match with 13 characters in 00:00:00.0000192
No match with 14 characters in 00:00:00.0000372
No match with 15 characters in 00:00:00.0000218
No match with 16 characters in 00:00:00.0000192
No match with 17 characters in 00:00:00.0000243
No match with 18 characters in 00:00:00.0000224
No match with 19 characters in 00:00:00.0000205
No match with 20 characters in 00:00:00.0000224
No match with 21 characters in 00:00:00.0000218
No match with 22 characters in 00:00:00.0000224
No match with 23 characters in 00:00:00.0000263
No match with 24 characters in 00:00:00.0000218
No match with 25 characters in 00:00:00.0000243
No match with 26 characters in 00:00:00.0000218
No match with 27 characters in 00:00:00.0000224
No match with 28 characters in 00:00:00.0000224
No match with 29 characters in 00:00:00.0000230
No match with 30 characters in 00:00:00.0000237
No match with 31 characters in 00:00:00.0000243
No match with 32 characters in 00:00:00.0000243&lt;/pre&gt;
&lt;p&gt;In other cases, some combination of alternation (the construct &amp;ldquo;|&amp;rdquo;) along with lookahead and lookbehind can be used to replace a regular expression that is subject to excessive backtracking. For example, regular expressions that are designed to match numbers are frequently troublesome if the numeric value can be either integral or floating point. A common pattern used to match such numeric values is ^\d+(|.\d+)*$, as shown in the following example.&lt;/p&gt;
&lt;pre class="code"&gt;[Visual Basic]
Imports System.Diagnostics
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()   
      Dim number As String = "111111111111111111111111111111!"
      Dim pattern As String = "^\d+(|.\d+)*$"
      
      Dim rgx As New Regex(pattern, RegexOptions.IgnoreCase)
      Dim sw As Stopwatch
      Dim str As String 
  
      For ctr As Integer = 1 To number.Length
         str = number.Substring(0, ctr)
         sw = Stopwatch.StartNew()
         If rgx.IsMatch(str) Then 
            Console.Write("Match with {0} characters ", str.Length)
         Else
            Console.Write("No match with {0} characters ", str.Length)
         End If  
         sw.Stop()
         Console.WriteLine("in {0}.", sw.Elapsed)
      Next
   End Sub
End Module&lt;/pre&gt;
&lt;pre class="code"&gt;[C#] 
using System;
using System.Diagnostics;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string number = "111111111111111111111111111111!";
      string pattern = @"^\d+(|.\d+)*$";
      
      Regex rgx = new Regex(pattern, 
                  RegexOptions.IgnoreCase);
      Stopwatch sw;
      string str; 
  
      for (int ctr = 1; ctr &amp;lt;= number.Length; ctr++) {
         str = number.Substring(0, ctr);
         sw = Stopwatch.StartNew();
         if (rgx.IsMatch(str)) 
            Console.Write("Match with {0} characters ", str.Length);
         else
            Console.Write("No match with {0} characters ", str.Length);

         sw.Stop();
         Console.WriteLine("in {0}.", sw.Elapsed);
      }
   }
}&lt;/pre&gt;
&lt;p&gt;However, as the output from the example shows, this pattern is subject to excessive backtracking.&lt;/p&gt;
&lt;pre class="code"&gt;Match with 1 characters in 00:00:00.0011311.
Match with 2 characters in 00:00:00.0010926.
Match with 3 characters in 00:00:00.0011003.
Match with 4 characters in 00:00:00.0014570.
Match with 5 characters in 00:00:00.0002797.
Match with 6 characters in 00:00:00.0001565.
Match with 7 characters in 00:00:00.0012619.
Match with 8 characters in 00:00:00.0001456.
Match with 9 characters in 00:00:00.0011439.
Match with 10 characters in 00:00:00.0010682.
Match with 11 characters in 00:00:00.0011125.
Match with 12 characters in 00:00:00.0002053.
Match with 13 characters in 00:00:00.0001854.
Match with 14 characters in 00:00:00.0012485.
Match with 15 characters in 00:00:00.0010675.
Match with 16 characters in 00:00:00.0011137.
Match with 17 characters in 00:00:00.0012299.
Match with 18 characters in 00:00:00.0001937.
Match with 19 characters in 00:00:00.0012709.
Match with 20 characters in 00:00:00.0011323.
Match with 21 characters in 00:00:00.0010996.
Match with 22 characters in 00:00:00.0010188.
Match with 23 characters in 00:00:00.0011125.
Match with 24 characters in 00:00:00.0001770.
Match with 25 characters in 00:00:00.0001469.
Match with 26 characters in 00:00:00.0001687.
Match with 27 characters in 00:00:00.0004356.
Match with 28 characters in 00:00:00.0013370.
Match with 29 characters in 00:00:00.0010958.
Match with 30 characters in 00:00:00.0010983.
No match with 31 characters in 00:00:03.0872118.&lt;/pre&gt;
&lt;p&gt;The root of the problem is that the subexpression &lt;span style="color: #ff0000;"&gt;(|.\d+)*&lt;/span&gt; is intended to match either a group separator or a decimal separator, but it also matches any other character. The subexpression also includes a nested quantifier. In the event of a near-match with numeric digits, the regular expression engine will have difficulty apportioning numeric digits between the first occurrence of the \d* pattern or its subsequent possible repetitions. &lt;/p&gt;
&lt;p&gt;A regular expression that eliminates this unnecessary backtracking and also addresses a number of limitations of the original regular expression is &lt;span style="color: #ff0000;"&gt;^\d*(,\d{3})*(?((?=\.))\.\d+|(?&amp;lt;=\d))$&lt;/span&gt;. This regular expression uses the conditional construct with an expression (for more information, see &lt;a href="http://msdn.microsoft.com/en-us/library/36xybswe.aspx"&gt;Alternation Constructs&lt;/a&gt; in the MSDN Library. Note that this regular expression works with numeric values formatted using the conventions of the English (United States) culture. A regular expression that uses the group and decimal separators of the current culture could be built dynamically by retrieving these values from the current culture&amp;rsquo;s &lt;strong&gt;DateTimeFormatInfo&lt;/strong&gt; object. The regular expression is interpreted as shown in the following table.&lt;/p&gt;
&lt;table style="width: 471px;" cellpadding="0" cellspacing="0" border="1"&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td width="130" valign="top"&gt;
&lt;p&gt;&lt;strong&gt;Pattern &lt;/strong&gt;&lt;/p&gt;
&lt;/td&gt;
&lt;td width="339" valign="top"&gt;
&lt;p&gt;&lt;strong&gt;Description&lt;/strong&gt;&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td width="130" valign="top"&gt;
&lt;p&gt;&lt;span style="color: #ff0000;"&gt;^&lt;/span&gt;&lt;/p&gt;
&lt;/td&gt;
&lt;td width="339" valign="top"&gt;
&lt;p&gt;Begin the match at the beginning of the string.&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td width="130" valign="top"&gt;
&lt;p&gt;&lt;span style="color: #ff0000;"&gt;\d*&lt;/span&gt;&lt;/p&gt;
&lt;/td&gt;
&lt;td width="339" valign="top"&gt;
&lt;p&gt;Match zero or more decimal digits. This matches the integral portion of the numeric value.&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td width="130" valign="top"&gt;
&lt;p&gt;&lt;span style="color: #ff0000;"&gt;(,\d{3})*&lt;/span&gt;&lt;/p&gt;
&lt;/td&gt;
&lt;td width="339" valign="top"&gt;
&lt;p&gt;Match zero or more occurrences of a group separator followed by three decimal digits.&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td width="130" valign="top"&gt;
&lt;p&gt;&lt;span style="color: #ff0000;"&gt;(?((?=\.))&lt;/span&gt;&lt;/p&gt;
&lt;/td&gt;
&lt;td width="339" valign="top"&gt;
&lt;p&gt;Use positive lookahead to determine whether the next character is a decimal separator. (This is the condition clause of an alternation pattern.) &lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td width="130" valign="top"&gt;
&lt;p&gt;&lt;span style="color: #ff0000;"&gt;\.\d+&lt;/span&gt;&lt;/p&gt;
&lt;/td&gt;
&lt;td width="339" valign="top"&gt;
&lt;p&gt;If the next character is a decimal separator, match the decimal separator followed by one or more decimal digits.&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td width="130" valign="top"&gt;
&lt;p&gt;&lt;span style="color: #ff0000;"&gt;|(?&amp;lt;=\d))&lt;/span&gt;&lt;/p&gt;
&lt;/td&gt;
&lt;td width="339" valign="top"&gt;
&lt;p&gt;If the next character is not a decimal separator, look behind to determine whether the previous character is a decimal digit. This ensures that the number contains at least one integral digit.&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td width="130" valign="top"&gt;
&lt;p&gt;&lt;span style="color: #ff0000;"&gt;$&lt;/span&gt;&lt;/p&gt;
&lt;/td&gt;
&lt;td width="339" valign="top"&gt;
&lt;p&gt;Match the end of the input string.&lt;/p&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;If this regular expression pattern replaces the pattern in the previous example, the example produces the following output:&lt;/p&gt;
&lt;pre class="code"&gt;Match with 1 characters in 00:00:00.0012331.
Match with 2 characters in 00:00:00.0010586.
Match with 3 characters in 00:00:00.0010509.
Match with 4 characters in 00:00:00.0011676.
Match with 5 characters in 00:00:00.0002303.
Match with 6 characters in 00:00:00.0001892.
Match with 7 characters in 00:00:00.0005203.
Match with 8 characters in 00:00:00.0014442.
Match with 9 characters in 00:00:00.0010740.
Match with 10 characters in 00:00:00.0010573.
Match with 11 characters in 00:00:00.0002046.
Match with 12 characters in 00:00:00.0002309.
Match with 13 characters in 00:00:00.0012318.
Match with 14 characters in 00:00:00.0001411.
Match with 15 characters in 00:00:00.0010900.
Match with 16 characters in 00:00:00.0010785.
Match with 17 characters in 00:00:00.0002008.
Match with 18 characters in 00:00:00.0002149.
Match with 19 characters in 00:00:00.0012850.
Match with 20 characters in 00:00:00.0011137.
No match with 21 characters in 00:00:00.0010887.&lt;/pre&gt;
&lt;h2&gt;Best Practices for Controlling Backtracking&lt;/h2&gt;
&lt;p&gt;To maximize the performance of regular expressions in the .NET Framework, we recommend that you do the following to limit or eliminate unnecessary backtracking:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;In alternation constructs, order alternatives based on their approximate frequency of occurrence in the input. &lt;/li&gt;
&lt;li&gt;Take the time to optimize alternation patterns. &lt;/li&gt;
&lt;li&gt;Determine whether backtracking is required for the regular expression to successfully match a subexpression with a portion of the input string. If it is not necessary, disable backtracking with the &lt;span style="color: #ff0000;"&gt;(?&amp;gt;subexpression)&lt;/span&gt; language element. &lt;/li&gt;
&lt;li&gt;If subexpressions are intended to validate input, replace nested quantifiers such as &lt;span style="color: #ff0000;"&gt;(\w*[A-Z])*&lt;/span&gt; with other language elements. The most useful language elements for this purpose are the positive lookahead assertion and the positive lookbehind assertion, the alternation construct, and the conditional construct. &lt;/li&gt;
&lt;/ul&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10045582" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/bclteam/archive/tags/RegEx/">RegEx</category></item><item><title>More on Zip in .NET [Richard Lee]</title><link>http://blogs.msdn.com/b/bclteam/archive/2010/07/29/more-on-zip-in-net-richard-lee.aspx</link><pubDate>Thu, 29 Jul 2010 23:21:29 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10044051</guid><dc:creator>BCL Team</dc:creator><slash:comments>11</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/bclteam/rsscomments.aspx?WeblogPostID=10044051</wfw:commentRss><comments>http://blogs.msdn.com/b/bclteam/archive/2010/07/29/more-on-zip-in-net-richard-lee.aspx#comments</comments><description>&lt;p&gt;First, I’d like to thank everybody for their comments on the Zip APIs. It’s great to know that I’m working on something that a lot of people will hopefully find useful. I’ll try to address the themes that came up in the comments.&lt;/p&gt;  &lt;h2&gt;Streams&lt;/h2&gt;  &lt;p&gt;A lot of the comments mentioned support for streams. The API does support creating a ZipArchive with a stream as the backing store, and input from streams. The following code sample takes the contents of instream and writes a Zip archive to outstream containing just that one file:&lt;/p&gt;  &lt;pre class="code"&gt;using (ZipArchive archive = new ZipArchive(outstream, ZipArchiveMode.Create))
{
	ZipArchiveEntry entry = archive.CreateEntry(&amp;quot;data.dat&amp;quot;);
	using (Stream entryStream = entry.Open())
	{
		instream.CopyTo(entryStream);
	}
}&lt;/pre&gt;

&lt;p&gt;This will write out the Zip archive directly to outstream, without buffering the entire contents of the archive in memory or writing to a temporary file. We really think of the methods used above as the core APIs. Methods like CreateEntryFromFile and ExtractToDirectory are purely convenience methods – their main purpose is to make some of the more common scenarios with files easier.&lt;/p&gt;

&lt;h2&gt;Compression and Encryption&lt;/h2&gt;

&lt;p&gt;Another common theme was custom encryption and compression algorithms. The vast majority of Zip archives that are meant to be interoperable with the widest range of libraries, tools, and applications use the Deflate compression algorithm without encryption. Our main goal for this API is to be able to read and write such archives. As such, we’re currently planning to support writing Zip archives with Deflate, reading Zip archives that use Deflate or no compression, and to not support encryption. Not only will this enable reading/writing interoperable Zip archives, it also scopes the work to something reasonable that can be delivered during my internship.&lt;/p&gt;

&lt;p&gt;If we’re not providing built-in support for additional compression or encryption algorithms, an obvious question, then, is why not provide extensibility hooks so that custom compression or encryption algorithms can be plugged-in? We explored doing this and it turns out it’d be more complex than you might initially think.&lt;/p&gt;

&lt;p&gt;A lot of people mentioned the CryptoStream and ICryptoTransform model as a powerful way to allow for extensibility. This works well because the ICryptoTransform only needs to do one thing – transform a series of bytes into another series of bytes. Unfortunately, encrypting Zip files is a much more complex operation. Fields and flags need to be set to appropriate values and headers need to be encrypted depending on which algorithm is used. Implementing either of the two secure encryption methods mentioned in the Zip specification would require access to essentially all of the metadata in the Zip file. The resulting interface for such an extension would be enormously complex.&lt;/p&gt;

&lt;p&gt;Compression is a bit simpler, as only one entry is compressed at a time. However, there are still fields and flags that need to be set in the headers, depending on the algorithm used. Furthermore, for both encryption and compression, only a few compression/encryption methods are specified in the Zip specification. We don’t want to give the impression that &lt;i&gt;any&lt;/i&gt; compression method can be used to produce a Zip file, when that isn’t the case. If you want to use a compression or encryption algorithm that isn’t specified in the Zip spec, you might as well just compress or encrypt the stream yourself.&lt;/p&gt;

&lt;p&gt;So an extensibility interface would be substantially more complex than something like ICryptoTransform, and add significant complexity to the ZipArchive/ZipArchiveEntry class. We don’t think providing extensibility hooks in this way adds enough value to the API to justify the added complexity that they bring. However, we are open to adding built-in support for encryption or other compression algorithms in the future, based on customer demand. We’ve specifically designed the API in a way that would allow us to do this. If this is something you’re interested in, we’d love to better understand your needs. &lt;/p&gt;

&lt;h2&gt;Abstract Base Class&lt;/h2&gt;

&lt;p&gt;Another common question was around providing a base class for Archives. We explored this and have decided not to add such an abstraction at this time. The main reason we are holding off is because right now we’re only planning to provide support for Zip archives and have no plans to support other archive formats (such as CAB, RAR, etc.). As a design principle, we try to avoid adding abstractions when there is only one implementation, otherwise we risk getting the abstraction wrong. Then we’re either stuck with the bad abstraction or are forced to add another when adding another implementation. All of this adds additional complexity that we’d like to avoid.&lt;/p&gt;

&lt;p&gt;The concerns about test-driven development are certainly valid, but there are ways around this. For example, because archives can be made with streams as the backing store, a FileStream could be mocked and put behind an archive. That may not be totally ideal, but these concerns don’t seem compelling enough to justify adding an abstract base class at this time.&lt;/p&gt;

&lt;h2&gt;Miscellaneous&lt;/h2&gt;

&lt;p&gt;There were a couple comments about treating the Zip archive like the filesystem, and supporting searching for certain kinds of files. We made the decision to treat the archive as a flat container of files because that is how they are actually stored. As a library rather than an application, we thought it made more sense to represent the archive as it exists on disk. Also, using LINQ on the entries means getting all of the files in a certain subdirectory that end in .txt is a relatively simple operation.&lt;/p&gt;

&lt;p&gt;Another interesting comment was that MoveTo was confusing. MoveTo was intended to act like Rename, for renaming entries but keeping everything else about them the same. The method was named MoveTo to mimic the naming for the method on FileInfo. However, because it is confusing and probably has very few compelling usage scenarios, we’re thinking of cutting it from the API.&lt;/p&gt;

&lt;p&gt;I hope I addressed some of your comments. We’d love to keep hearing from you, especially if you have extremely compelling use cases for some of the features that we’re not including in this version of the API. Being the designer of the API, I think it would be really cool, too, to support custom compression and encryption, or some of these other features. But at the risk of sounding like a broken record, I’m trying to build a simple, usable API, and these decisions are made with that in mind.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10044051" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/bclteam/archive/tags/System-IO/">System.IO</category><category domain="http://blogs.msdn.com/b/bclteam/archive/tags/ZIP/">ZIP</category></item><item><title>Working with Zip Files in .NET [Richard Lee]</title><link>http://blogs.msdn.com/b/bclteam/archive/2010/06/28/working-with-zip-files-in-net.aspx</link><pubDate>Mon, 28 Jun 2010 21:37:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10031785</guid><dc:creator>BCL Team</dc:creator><slash:comments>38</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/bclteam/rsscomments.aspx?WeblogPostID=10031785</wfw:commentRss><comments>http://blogs.msdn.com/b/bclteam/archive/2010/06/28/working-with-zip-files-in-net.aspx#comments</comments><description>&lt;p&gt;Before getting started, I&amp;rsquo;ll introduce myself. My name is Richard Lee, and I&amp;rsquo;m a developer intern on the BCL for the summer. I&amp;rsquo;ve only been here for a few weeks, but it&amp;rsquo;s been great working here. The people, the environment, and my project are all great. Speaking of which, my project is to add general purpose .NET APIs for reading and writing Zip files, which we&amp;rsquo;re considering adding to the next version of the .NET Framework.&lt;/p&gt;
&lt;p&gt;The most common Zip tasks are extracting to a directory and archiving a directory. For these mainline scenarios, we have static convenience methods. The following code takes all of the files in the Zip file, photos.zip, and extracts them to a folder on the file system:&lt;/p&gt;
&lt;pre class="code"&gt;ZipArchive.ExtractToDirectory("photos.zip", @"photos\summer2010");&lt;/pre&gt;
&lt;p&gt;This code does the reverse, putting all of the files in the folder into the Zip file:&lt;/p&gt;
&lt;pre class="code"&gt;ZipArchive.CreateFromDirectory(@"docs\attach", "attachment.zip");&lt;/pre&gt;
&lt;p&gt;For more sophisticated manipulations of Zip archives, there are two main classes. ZipArchive represents a zip archive, which is a collection of entries, and ZipArchiveEntry represents an archived file entry. The following code extracts only text files from the given archive.&lt;/p&gt;
&lt;pre class="code"&gt;using (var archive = new ZipArchive("data.zip"))
{
    foreach (var entry in archive.Entries)
    {
        if (entry.FullName.EndsWith(".txt", StringComparison.OrdinalIgnoreCase))
        {
            entry.ExtractToFile(Path.Combine(directory, entry.FullName));
        }
    }
}&lt;/pre&gt;
&lt;p&gt;Zip archives can also be created on-the-fly. This example creates a new archive with a readme file that is created without the need for a corresponding file on disk, and a file from the file system.&lt;/p&gt;
&lt;pre class="code"&gt;using (var archive = new ZipArchive("new.zip", ZipArchiveMode.Create))
{
    var readmeEntry = archive.CreateEntry("Readme.txt");
    using (var writer = new StreamWriter(readmeEntry.Open()))
    {
        writer.WriteLine("Included files: ");
        writer.WriteLine("data.dat");
    }

    archive.CreateEntryFromFile("data.dat", "data.dat");
}&lt;/pre&gt;
&lt;p&gt;The ZipArchive class supports three modes:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;In Read mode, data is read from the file on demand, using only a small buffer. &lt;/li&gt;
&lt;li&gt;In Create mode, data is written directly to the file using only a small buffer. Only one entry may be held open for writing at a time. &lt;/li&gt;
&lt;li&gt;In Update mode it is possible to read and write from existing archives, as well as rename or delete entries. This mode requires loading the entire archive into memory, and as such we recommend that it be used only with small archives when this functionality is needed. &lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Below is our current thinking on what the public API listing will look like (note that this hasn&amp;rsquo;t been finalized yet). &lt;/p&gt;
&lt;pre class="code"&gt;namespace System.IO.Compression
{
    public enum ZipArchiveMode { Read, Create, Update }

    public class ZipArchive : IDisposable {
        // Constructors
        public ZipArchive(String path);
        public ZipArchive(String path, ZipArchiveMode mode); 
        public ZipArchive(Stream stream);
        public ZipArchive(Stream stream, ZipArchiveMode mode);
        public ZipArchive(Stream stream, ZipArchiveMode mode, Boolean leaveOpen);

        // Properties
        public ReadOnlyCollection&amp;lt;ZipArchiveEntry&amp;gt; Entries { get; }
        public ZipArchiveMode Mode { get; }
        
        // Instance methods
        public ZipArchiveEntry GetEntry(String entryName);
        public ZipArchiveEntry CreateEntry(String entryName);

        public void Dispose();
        protected virtual void Dispose(Boolean disposing);

        public override String ToString();

        // Instance convenience methods
        public ZipArchiveEntry CreateEntryFromFile(String sourceFileName, String entryName);

        public void ExtractToDirectory(String destinationDirectoryName);

        // Static convenience methods
        public static void CreateFromDirectory(String sourceDirectoryName, String destinationArchive);
        public static void CreateFromDirectory(String sourceDirectoryName, String destinationArchive, Boolean includeBaseDirectory);

        public static void ExtractToDirectory(String sourceArchive, String destinationDirectoryName);
    }

    public class ZipArchiveEntry {
        // Properties
        public DateTimeOffset LastWriteTime { get; set; }
        public String FullName { get; }
        public String Name { get; }
        public Int64 Length { get; }
        public Int64 CompressedLength { get; }
        public ZipArchive Archive { get; }

        // Methods
        public Stream Open();
        public void Delete();
        public void MoveTo(String destinationEntryName);

        // Convenience methods
        public void ExtractToFile(String destinationFileName);
        public void ExtractToFile(String destinationFileName, Boolean overwrite);

        public override String ToString();
    }
}&lt;/pre&gt;
&lt;p&gt;We would love to hear what you think of the APIs so far, and how you plan on using them.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10031785" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/bclteam/archive/tags/System-IO/">System.IO</category><category domain="http://blogs.msdn.com/b/bclteam/archive/tags/ZIP/">ZIP</category></item><item><title>Optimizing Regular Expression Performance, Part I: Working with the Regex Class and Regex Objects [Ron Petrusha]</title><link>http://blogs.msdn.com/b/bclteam/archive/2010/06/25/optimizing-regular-expression-performance-part-i-working-with-the-regex-class-and-regex-objects.aspx</link><pubDate>Fri, 25 Jun 2010 08:29:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10013913</guid><dc:creator>BCL Team</dc:creator><slash:comments>5</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/bclteam/rsscomments.aspx?WeblogPostID=10013913</wfw:commentRss><comments>http://blogs.msdn.com/b/bclteam/archive/2010/06/25/optimizing-regular-expression-performance-part-i-working-with-the-regex-class-and-regex-objects.aspx#comments</comments><description>&lt;p&gt;The .NET Framework’s regular expression implementation is a traditional Nondeterministic Finite Automaton (NFA) engine. Perhaps the most significant feature of NFA engines is that they place the responsibility for crafting efficient, high-performance regular expressions on the developer. (For more information about the .NET Framework’s implementation of an NFA engine, see &lt;a href="http://msdn.microsoft.com/en-us/library/e347654k.aspx"&gt;Details of Regular Expression Behavior&lt;/a&gt; in the MSDN Library.) With their support for such features as backreferences and backtracking, NFA engines often offer a trade-off between flexibility and power on the one hand, and speed and performance on the other. Many regular expression developers complain about the performance of the regular expression engine but are often unable to diagnose why an individual regular expression performs poorly. In this three-part article, we’ll discuss some of the techniques that regular expression developers can apply to maximize the performance of regular expressions while preserving their power.&lt;/p&gt;  &lt;p&gt;At the heart of the .NET Framework’s regular expression object model is the &lt;b&gt;Regex&lt;/b&gt; object, which represents the regular expression engine. Often, the single greatest factor that affects regular expression performance is the way in which the &lt;b&gt;Regex&lt;/b&gt; engine is used. Defining a regular expression involves tightly coupling the regular expression engine with a regular expression pattern. That coupling process, whether it involves instantiating a &lt;b&gt;Regex&lt;/b&gt; object by passing its constructor a regular expression pattern or calling a static method by passing it the regular expression pattern along with the string to be analyzed, is by necessity an expensive one. If the regular expression engine will be used in instance method calls, an instance of the regular expression engine must be created. All regular expressions, whether used by &lt;b&gt;Regex&lt;/b&gt; instances or in static &lt;b&gt;Regex&lt;/b&gt; method calls, must then be compiled (more on this later). This is analogous to recompiling an application each time that it is run.&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;b&gt;Note:&lt;/b&gt; To measure regular expression performance, we make extensive use of the &lt;b&gt;Stopwatch&lt;/b&gt; class. These measurements are used for illustrative purposes only; they reflect performance when a particular regular expression is used to parse a particular input string on a particular system. They are not intended to be construed as objective benchmarks. &lt;/p&gt; &lt;/blockquote&gt;  &lt;h2&gt;Taking Advantage of the Regular Expression Cache&lt;/h2&gt;  &lt;p&gt;Since the process of coupling the regular expression engine with a particular pattern is expensive, you can improve performance by ensuring that you perform this coupling as few times as possible. The following example illustrates a fairly common scenario that offers poor performance. An &lt;b&gt;IsValidEmail&lt;/b&gt; method is called whenever an application needs to validate an email address. The method instantiates a &lt;b&gt;Regex&lt;/b&gt; object and calls its &lt;b&gt;IsMatch&lt;/b&gt; method to process the email address. This means that a &lt;b&gt;Regex&lt;/b&gt; object is instantiated with the same regular expression pattern with each method call.&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;b&gt;Note:&lt;/b&gt; The practice of repeatedly instantiating a &lt;b&gt;Regex&lt;/b&gt; object with the same regular expression, as the performance measurements presented later in this section show, represents a worst practice that significantly degrades performance. Do not replicate this practice in your own code. &lt;/p&gt; &lt;/blockquote&gt;  &lt;pre class="code"&gt;[Visual Basic]
Imports System.Diagnostics
Imports System.Text.RegularExpressions

Module Example
  Public Sub Main()
    Dim inputs() As String = { &amp;quot;david.jones@proseware.com&amp;quot;, _
                               &amp;quot;d.j@server1.proseware.com&amp;quot;, _
                               &amp;quot;jones@ms1.proseware.com&amp;quot;, _
                               &amp;quot;j.@server1.proseware.com&amp;quot;, _
                               &amp;quot;j@proseware.com9&amp;quot;, _
                               &amp;quot;js#internal@proseware.com&amp;quot;, _
                               &amp;quot;j_9@[129.126.118.1]&amp;quot;, _
                               &amp;quot;j..s@proseware.com&amp;quot;, _
                               &amp;quot;js*@proseware.com&amp;quot;, _
                               &amp;quot;js@proseware..com&amp;quot;, _
                               &amp;quot;js@proseware.com9&amp;quot;, _
                               &amp;quot;j.s@server1.proseware.com&amp;quot;, _
                               &amp;quot;&amp;quot;&amp;quot;a*****&amp;quot;&amp;quot;&amp;quot;&amp;quot;@cohowinery.com&amp;quot;, _
                         webmaster@aaaabbbbbbbbccccccccddddd!&amp;quot; }
    Dim sw As Stopwatch = Stopwatch.StartNew()
    For Each input As String In inputs
      If IsValidEmail(input) Then
        ' Handle valid data.
        Console.WriteLine(&amp;quot;{0} is a valid email address.&amp;quot;, _
                          input)
      Else
        ' Handle invalid data.
        Console.WriteLine(&amp;quot;{0} is not a valid email address.&amp;quot;, _
                          input)
      End If
    Next 
    sw.Stop()
    Console.WriteLine(&amp;quot;Elapsed time: {0}&amp;quot;, sw.Elapsed)
  End Sub
   
  Private Function IsValidEmail(input As String) As Boolean
    Dim pattern As String = &amp;quot;^(?(&amp;quot;&amp;quot;)(&amp;quot;&amp;quot;.+?&amp;quot;&amp;quot;@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&amp;amp;'\*\+/=\?\^`\{\}\|~\w])*)(?&amp;lt;=[0-9a-zA-Z])@))&amp;quot; + _
                             &amp;quot;(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$&amp;quot;
      Dim rgx As New Regex(pattern)    ' BAD: Never reinstantiate the same object
      Return rgx.IsMatch(input)
   End Function
End Module

[C#]
using System;
using System.Diagnostics;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      Example ex = new Example();
      string[] inputs = { &amp;quot;david.jones@proseware.com&amp;quot;, 
                          &amp;quot;d.j@server1.proseware.com&amp;quot;, 
                          &amp;quot;jones@ms1.proseware.com&amp;quot;, 
                          &amp;quot;j.@server1.proseware.com&amp;quot;, 
                          &amp;quot;j@proseware.com9&amp;quot;, 
                          &amp;quot;js#internal@proseware.com&amp;quot;, 
                          &amp;quot;j_9@[129.126.118.1]&amp;quot;, 
                          &amp;quot;j..s@proseware.com&amp;quot;, 
                          &amp;quot;js*@proseware.com&amp;quot;, 
                          &amp;quot;js@proseware..com&amp;quot;, 
                          &amp;quot;js@proseware.com9&amp;quot;, 
                          &amp;quot;j.s@server1.proseware.com&amp;quot;, 
                          @&amp;quot;&amp;quot;&amp;quot;a*****&amp;quot;&amp;quot;@cohowinery.com&amp;quot;, 
                          &amp;quot;webmaster@aaaabbbbbbbbccccccccddddd!&amp;quot; };
      Stopwatch sw = Stopwatch.StartNew();
      foreach (string input in inputs) {
         if (ex.IsValidEmail(input))
            // Handle valid email data.
            Console.WriteLine(&amp;quot;{0} is a valid email address.&amp;quot;, input);
         else
            // Handle invalid data.
            Console.WriteLine(&amp;quot;{0} is not a valid email address.&amp;quot;,
                              input);
      } 
      sw.Stop();
      Console.WriteLine(&amp;quot;Elapsed time: {0}&amp;quot;, sw.Elapsed);
   }

   private bool IsValidEmail(string input)
   {
      string pattern = @&amp;quot;^(?(&amp;quot;&amp;quot;)(&amp;quot;&amp;quot;.+?&amp;quot;&amp;quot;@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&amp;amp;'\*\+/=\?\^`\{\}\|~\w])*)(?&amp;lt;=[0-9a-zA-Z])@))&amp;quot; + 
                       @&amp;quot;(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$&amp;quot;;
      Regex rgx = new Regex(pattern);   // BAD: Never reinstantiate the same object

      return rgx.IsMatch(input);   
   }
}&lt;/pre&gt;

&lt;p&gt;This example displays the following output:&lt;/p&gt;

&lt;pre class="code"&gt;david.jones@proseware.com is a valid email address.
d.j@server1.proseware.com is a valid email address.
jones@ms1.proseware.com is a valid email address.
j.@server1.proseware.com is not a valid email address.
j@proseware.com9 is not a valid email address.
js#internal@proseware.com is a valid email address.
j_9@[129.126.118.1] is a valid email address.
j..s@proseware.com is not a valid email address.
js*@proseware.com is not a valid email address.
js@proseware..com is not a valid email address.
js@proseware.com9 is not a valid email address.
j.s@server1.proseware.com is a valid email address.
&amp;quot;a*****&amp;quot;&amp;quot;@cohowinery.com is a valid email address.
webmaster@aaaabbbbbbbbccccccccddddd! is not a valid email address.
Elapsed time: 00:00:00.4997749&lt;/pre&gt;

&lt;p&gt;Performance suffers here because each method call requires a &lt;b&gt;Regex&lt;/b&gt; object to be instantiated with the same regular expression pattern. But instead of instantiating a Regex object in each method call, we can call the static &lt;b&gt;Regex.IsMatch&lt;/b&gt; method, as the following example does.&lt;/p&gt;

&lt;pre class="code"&gt;[Visual Basic]
Imports System.Diagnostics
Imports System.Text.RegularExpressions

Module Example
  Public Sub Main()
    Dim inputs() As String = { &amp;quot;david.jones@proseware.com&amp;quot;, _
                               &amp;quot;d.j@server1.proseware.com&amp;quot;, _
                               &amp;quot;jones@ms1.proseware.com&amp;quot;, _
                               &amp;quot;j.@server1.proseware.com&amp;quot;, _
                               &amp;quot;j@proseware.com9&amp;quot;, _
                               &amp;quot;js#internal@proseware.com&amp;quot;, _
                               &amp;quot;j_9@[129.126.118.1]&amp;quot;, _
                               &amp;quot;j..s@proseware.com&amp;quot;, _
                               &amp;quot;js*@proseware.com&amp;quot;, _
                               &amp;quot;js@proseware..com&amp;quot;, _
                               &amp;quot;js@proseware.com9&amp;quot;, _
                               &amp;quot;j.s@server1.proseware.com&amp;quot;, _
                               &amp;quot;&amp;quot;&amp;quot;a*****&amp;quot;&amp;quot;&amp;quot;&amp;quot;@cohowinery.com&amp;quot;, _
                         webmaster@aaaabbbbbbbbccccccccddddd!&amp;quot; }
    Dim sw As Stopwatch = Stopwatch.StartNew()
    For Each input As String In inputs
      If IsValidEmail(input) Then
        ' Handle valid data.
        Console.WriteLine(&amp;quot;{0} is a valid email address.&amp;quot;, _
                          input)
      Else
        ' Handle invalid data.
        Console.WriteLine(&amp;quot;{0} is not a valid email address.&amp;quot;, _
                          input)
      End If
    Next 
    sw.Stop()
    Console.WriteLine(&amp;quot;Elapsed time: {0}&amp;quot;, sw.Elapsed)
  End Sub
   
  Private Function IsValidEmail(input As String) As Boolean
    Dim pattern As String = &amp;quot;^(?(&amp;quot;&amp;quot;)(&amp;quot;&amp;quot;.+?&amp;quot;&amp;quot;@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&amp;amp;'\*\+/=\?\^`\{\}\|~\w])*)(?&amp;lt;=[0-9a-zA-Z])@))&amp;quot; + _
                             &amp;quot;(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$&amp;quot;
      Return Regex.IsMatch(input, pattern)  ' GOOD: Take advantage of regex cache
   End Function
End Module

[C#]
using System;
using System.Diagnostics;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      Example ex = new Example();
      string[] inputs = { &amp;quot;david.jones@proseware.com&amp;quot;, 
                          &amp;quot;d.j@server1.proseware.com&amp;quot;, 
                          &amp;quot;jones@ms1.proseware.com&amp;quot;, 
                          &amp;quot;j.@server1.proseware.com&amp;quot;, 
                          &amp;quot;j@proseware.com9&amp;quot;, 
                          &amp;quot;js#internal@proseware.com&amp;quot;, 
                          &amp;quot;j_9@[129.126.118.1]&amp;quot;, 
                          &amp;quot;j..s@proseware.com&amp;quot;, 
                          &amp;quot;js*@proseware.com&amp;quot;, 
                          &amp;quot;js@proseware..com&amp;quot;, 
                          &amp;quot;js@proseware.com9&amp;quot;, 
                          &amp;quot;j.s@server1.proseware.com&amp;quot;, 
                          @&amp;quot;&amp;quot;&amp;quot;a*****&amp;quot;&amp;quot;@cohowinery.com&amp;quot;, 
                          &amp;quot;webmaster@aaaabbbbbbbbccccccccddddd!&amp;quot; };
      Stopwatch sw = Stopwatch.StartNew();
      foreach (string input in inputs) {
         if (ex.IsValidEmail(input))
            // Handle valid email data.
            Console.WriteLine(&amp;quot;{0} is a valid email address.&amp;quot;, input);
         else
            // Handle invalid data.
            Console.WriteLine(&amp;quot;{0} is not a valid email address.&amp;quot;,
                              input);
      } 
      sw.Stop();
      Console.WriteLine(&amp;quot;Elapsed time: {0}&amp;quot;, sw.Elapsed);
   }

   private bool IsValidEmail(string input)
   {
      string pattern = @&amp;quot;^(?(&amp;quot;&amp;quot;)(&amp;quot;&amp;quot;.+?&amp;quot;&amp;quot;@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&amp;amp;'\*\+/=\?\^`\{\}\|~\w])*)(?&amp;lt;=[0-9a-zA-Z])@))&amp;quot; + 
                       @&amp;quot;(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$&amp;quot;;
      return Regex.IsMatch(input, pattern);  // GOOD: Take advantage of regex cache
   }
}&lt;/pre&gt;

&lt;p&gt;The following output is displayed when the call to the instance &lt;b&gt;Regex.IsMatch&lt;/b&gt; method is replaced by the equivalent call to the static &lt;b&gt;Regex.IsMatch&lt;/b&gt; method:&lt;/p&gt;

&lt;pre class="code"&gt;david.jones@proseware.com is a valid email address.
d.j@server1.proseware.com is a valid email address.
jones@ms1.proseware.com is a valid email address.
j.@server1.proseware.com is not a valid email address.
j@proseware.com9 is not a valid email address.
js#internal@proseware.com is a valid email address.
j_9@[129.126.118.1] is a valid email address.
j..s@proseware.com is not a valid email address.
js*@proseware.com is not a valid email address.
js@proseware..com is not a valid email address.
js@proseware.com9 is not a valid email address.
j.s@server1.proseware.com is a valid email address.
&amp;quot;a*****&amp;quot;&amp;quot;@cohowinery.com is a valid email address.
webmaster@aaaabbbbbbbbccccccccddddd! is not a valid email address.
Elapsed time: 00:00:00.0380847&lt;/pre&gt;

&lt;p&gt;The following chart illustrates the difference in performance between the first example, which relies on repeatedly instantiating a &lt;b&gt;Regex&lt;/b&gt; object with the same regular expression pattern to call an instance matching method, and the second, which calls a static matching method.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-30-50-metablogapi/2084.clip_5F00_image002_5F00_1EEC4F9F.gif"&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="clip_image002" border="0" alt="clip_image002" src="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-30-50-metablogapi/5621.clip_5F00_image002_5F00_thumb_5F00_61E81E0C.gif" width="441" height="237" /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The execution time of the first example is about 15 times the execution time of the second example. The difference in performance is due to the caching of regular expressions used in static method calls. Whereas the first example instantiates a regular expression object and converts the regular expression into opcodes in each of fourteen method calls (one for each element in the string array), the second example performs this conversion only once, on the first method call. Subsequently, it retrieves the interpreted regular expression.from the cache each time the expression is needed. &lt;/p&gt;

&lt;p&gt;Only regular expressions used in static method calls are cached; regular expressions used in instance methods are not. The size of the cache is defined by the &lt;b&gt;Regex.CacheSize&lt;/b&gt; property. By default, 15 regular expressions are cached, although this value can be modified if necessary. If the number of regular expressions exceeds the cache size, the regular expression engine discards the least recently used regular expression to cache the newest one. &lt;/p&gt;

&lt;p&gt;Note that there is a breaking change in regular expression caching between versions 1.1 and subsequent versions of the .NET Framework. In version 1.1, both instance and static regular expressions are cached; in version 2.0 and all subsequent versions, only regular expressions used in static method calls are cached. For more information, see &lt;a href="http://blogs.msdn.com/bclteam/archive/2006/10/19/regex-class-caching-changes-between-net-framework-1-1-and-net-framework-2-0-josh-free.aspx"&gt;Regex Class Caching Changes between .NET Framework 1.1 and .NET Framework 2.0&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;Options for Building Regular Expressions &lt;/h2&gt;

&lt;p&gt;So far, we’ve focused on using static regular expression methods rather than repeatedly re-instantiating the same regular expression object. You can obtain additional performance benefits by using compiled regular expressions when appropriate. (For more information, see &lt;a href="http://msdn.microsoft.com/en-us/library/8zbs0h2f.aspx"&gt;Compilation and Reuse&lt;/a&gt;.)&lt;/p&gt;

&lt;p&gt;The regular expression engine builds regular expressions in the .NET Framework in three different ways:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;It interprets them. That is, when a regular expression object is instantiated, or when a static regular expression method is called and the regular expression cannot be found in the cache, the regular expression engine converts the regular expressions to opcodes. When a method is called, the opcodes are converted to MSIL and executed.by the JIT compiler. Interpreted regular expressions can be used in both static and instance method calls. Interpreted regular expressions reduce startup time at the cost of slower execution time. &lt;/li&gt;

  &lt;li&gt;It compiles them. That is, when a regular expression object is instantiated, or when a static regular expression method is called and the regular expression cannot be found in the cache, the regular expression engine converts the regular expressions to MSIL. When a method is called, the MSIL is executed by the JIT compiler. Compiled regular expressions can be used in both static and instance method calls. Compiled regular expressions increase execution speed at the cost of longer startup times. &lt;/li&gt;

  &lt;li&gt;It compiles them into a separate assembly. That is, the static &lt;b&gt;Regex.CompileToAssembly&lt;/b&gt; method is used to compile one or more regular expression patterns as MSIL into a separate assembly, where the regular expression engine and each regular expression pattern is tightly coupled into a class that derives from &lt;b&gt;Regex&lt;/b&gt;. When the regular expression object is instantiated, its MSIL is loaded from its assembly and executed by the JIT compiler. Regular expressions compiled to a special-purpose assembly can be used only in instance method calls. Regular expressions that are compiled to assemblies move much of a regular expression’s startup cost from runtime to design time. In a run-time environment, they maximize performance both at startup and during execution. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;These three ways of using a regular expression represent three different tradeoffs between performance at startup and runtime execution. Let’s look at each of the three.&lt;/p&gt;

&lt;h2&gt;Interpreted Regular Expressions&lt;/h2&gt;

&lt;p&gt;Interpreted regular expressions sacrifice execution speed for reduced startup time, so they are best used when the regular expression is limited to a small number of method calls. This is illustrated by the following example, which compares the performance of an interpreted and a compiled regular expression when extracting a sentence from a file that contains a one-sentence string. &lt;/p&gt;

&lt;pre class="code"&gt;[Visual Basic]
Imports System.Diagnostics
Imports System.IO
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim pattern As String = &amp;quot;\b(\w+((\r?\n)|,?\s))*\w+[.?:;!]&amp;quot;
      Dim input As String = New StreamReader(&amp;quot;.\OneSentence.txt&amp;quot;).ReadToEnd()
      Dim sw As Stopwatch

      Console.WriteLine(&amp;quot;***Interpreted regular expressions***&amp;quot;)
      ' Use Regex.Matches method to find all matches.
      sw = Stopwatch.StartNew()
      Dim instRegex As New Regex(pattern, RegexOptions.Singleline)
      Dim matches As MatchCollection = instRegex.Matches(input)
      For Each match As Match In matches
         ' Do nothing. If necessary, the MatchCollection will be populated using
         ' lazy evaluation.
      Next
      sw.Stop()
      Console.WriteLine(&amp;quot;Found {0} matches in {1} using regex.Matches()&amp;quot;,
                        matches.Count, sw.Elapsed)

      ' Use Regex.Match method followed by Match.NextMatch to find all matches.
      sw = Stopwatch.StartNew()
      Dim ctr As Integer = 0
      Dim instRegex2 As New Regex(pattern, RegexOptions.Multiline)
      Dim match2 As Match = instRegex2.Match(input)
      If match2.Success Then
         Do
            ctr += 1
            match2 = match2.NextMatch()
         Loop While match2.Success
      End If
      sw.Stop()
      Console.WriteLine(&amp;quot;Found {0} matches in {1} using regex.Match()/NextMatch()&amp;quot;,
                        ctr, sw.Elapsed)

      ' Use Regex.Match(String, Int32) to find all matches.
      sw = Stopwatch.StartNew()
      Dim pos As Integer = 0
      Dim ctr2 As Integer = 0
      Dim instRegex3 As New Regex(pattern, RegexOptions.Multiline)
      Dim match3 As Match
      Do
         match3 = instRegex3.Match(input, pos)
         If match3.Success Then
            ctr2 += 1
            pos = match3.Index + match3.Length
         End If
      Loop While match3.Success And pos &amp;lt;= input.Length
      sw.Stop()
      Console.WriteLine(&amp;quot;Found {0} matches in {1} using regex.Match(String, Int32)&amp;quot;,
                        ctr2, sw.Elapsed)

      Console.WriteLine()
      Console.WriteLine(&amp;quot;***Compiled regular expressions***&amp;quot;)

      ' Use compiled Regex.Matches method to find all matches.
      sw = Stopwatch.StartNew()
      Dim instRegexC As New Regex(pattern, RegexOptions.Multiline Or RegexOptions.Compiled)
      Dim matchesC As MatchCollection = instRegexC.Matches(input)
      For Each matchC As Match In matchesC
         ' Do nothing. If necessary, the MatchCollection will be populated using
         ' lazy evaluation.
      Next
      sw.Stop()
      Console.WriteLine(&amp;quot;Found {0} matches in {1} using compiled regex.Matches()&amp;quot;,
                        matchesC.Count, sw.Elapsed)

      ' Use compiled Regex.Match method followed by Match.NextMatch to find all matches.
      sw = Stopwatch.StartNew()
      Dim ctrC As Integer = 0
      Dim instRegex2c As New Regex(pattern, RegexOptions.Multiline Or RegexOptions.Compiled)
      Dim match2c As Match = instRegex2c.Match(input)
      If match2c.Success Then
         Do
            ctrC += 1
            match2c = match2c.NextMatch()
         Loop While match2c.Success
      End If
      sw.Stop()
      Console.WriteLine(&amp;quot;Found {0} matches in {1} using compiled regex.Match/NextMatch&amp;quot;,
                        ctrC, sw.Elapsed)

      ' Use compiled Regex.Match(String, Int32) to find all matches.
      sw = Stopwatch.StartNew()
      Dim posC As Integer = 0
      Dim ctr2c As Integer = 0
      Dim instRegex3c As New Regex(pattern, RegexOptions.Multiline Or RegexOptions.Compiled)
      Dim match3c As Match
      Do
         match3c = instRegex3c.Match(input, posC)
         If match3c.Success Then
            ctr2c += 1
            posC = match3c.Index + match3c.Length
         End If
      Loop While match3c.Success And posC &amp;lt;= input.Length
      sw.Stop()
      Console.WriteLine(&amp;quot;Found {0} matches in {1} using compiled regex.Match(String, Int32)&amp;quot;,
                        ctr2c, sw.Elapsed)
   End Sub
End Module

[C#]
using System;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern = @&amp;quot;\b(\w+((\r?\n)|,?\s))*\w+[.?:;!]&amp;quot;;
      string input = new StreamReader(@&amp;quot;.\OneSentence.txt&amp;quot;).ReadToEnd();
      Stopwatch sw;

      Console.WriteLine(&amp;quot;***Interpreted regular expressions***&amp;quot;);
      // Use Regex.Matches method to find all matches.
      sw = Stopwatch.StartNew();
      Regex instRegex = new Regex(pattern, RegexOptions.Singleline);
      MatchCollection matches = instRegex.Matches(input);
      foreach (Match match in matches)
      {
         // Do nothing. If necessary, the MatchCollection will be populated using
         // lazy evaluation.
      }
      sw.Stop();
      Console.WriteLine(&amp;quot;Found {0} matches in {1} using regex.Matches();&amp;quot;,
                        matches.Count, sw.Elapsed);

      // Use Regex.Match method followed by Match.NextMatch to find all matches.
      sw = Stopwatch.StartNew();
      int ctr = 0;
      Regex instRegex2 = new Regex(pattern, RegexOptions.Multiline);
      Match match2 = instRegex2.Match(input);
      if (match2.Success)
      {
         do
         {
            ctr++;
            match2 = match2.NextMatch();
         } while (match2.Success);
      }
      sw.Stop();
      Console.WriteLine(&amp;quot;Found {0} matches in {1} using regex.Match();/NextMatch();&amp;quot;,
                        ctr, sw.Elapsed);

      // Use Regex.Match(String, Int32); to find all matches.
      sw = Stopwatch.StartNew();
      int pos = 0;
      int ctr2 = 0;
      Regex instRegex3 = new Regex(pattern, RegexOptions.Multiline);
      Match match3;
      do
      {
         match3 = instRegex3.Match(input, pos);
         if (match3.Success)
         {
            ctr2++;
            pos = match3.Index + match3.Length;
         }
      } while (match3.Success &amp;amp; pos &amp;lt;= input.Length);
      sw.Stop();
      Console.WriteLine(&amp;quot;Found {0} matches in {1} using regex.Match(String, Int32);&amp;quot;,
                        ctr2, sw.Elapsed);

      Console.WriteLine();
      Console.WriteLine(&amp;quot;***Compiled regular expressions***&amp;quot;);

      // Use compiled Regex.Matches method to find all matches.
      sw = Stopwatch.StartNew();
      Regex instRegexC = new Regex(pattern, RegexOptions.Multiline | RegexOptions.Compiled);
      MatchCollection matchesC = instRegexC.Matches(input);
      foreach (Match matchC in matchesC)
      {
         // Do nothing. If necessary, the MatchCollection will be populated using
         // lazy evaluation.
      }
      sw.Stop();
      Console.WriteLine(&amp;quot;Found {0} matches in {1} using compiled regex.Matches();&amp;quot;,
                        matchesC.Count, sw.Elapsed);

      // Use compiled Regex.Match method followed by Match.NextMatch to find all matches.
      sw = Stopwatch.StartNew();
      int ctrC = 0;
      Regex instRegex2c = new Regex(pattern, RegexOptions.Multiline | RegexOptions.Compiled);
      Match match2c = instRegex2c.Match(input);
      if (match2c.Success)
      {
         do
         {
            ctrC++;
            match2c = match2c.NextMatch();
         } while (match2c.Success);
      }
      sw.Stop();
      Console.WriteLine(&amp;quot;Found {0} matches in {1} using compiled regex.Match/NextMatch&amp;quot;,
                        ctrC, sw.Elapsed);

      // Use compiled Regex.Match(String, Int32); to find all matches.
      sw = Stopwatch.StartNew();
      int posC = 0;
      int ctr2c = 0;
      Regex instRegex3c = new Regex(pattern, RegexOptions.Multiline | RegexOptions.Compiled);
      Match match3c;
      do
      {
         match3c = instRegex3c.Match(input, posC);
         if (match3c.Success)
         {
            ctr2c++;
            posC = match3c.Index + match3c.Length;
         }
      } while (match3c.Success &amp;amp; posC &amp;lt;= input.Length);
      sw.Stop();
      Console.WriteLine(&amp;quot;Found {0} matches in {1} using compiled regex.Match(String, Int32);&amp;quot;,
                        ctr2c, sw.Elapsed);
   }
}&lt;/pre&gt;

&lt;p&gt;As the following output and chart show, the interpreted regular expression is significantly faster than its compiled counterpart. &lt;/p&gt;

&lt;pre class="code"&gt;***Interpreted regular expressions***
Found 1 matches in 00:00:00.0014471 using regex.Matches()
Found 1 matches in 00:00:00.0000689 using regex.Match()/NextMatch()
Found 1 matches in 00:00:00.0000656 using regex.Match(String, Int32)

***Compiled regular expressions***
Found 1 matches in 00:00:00.0079332 using compiled regex.Matches()
Found 1 matches in 00:00:00.0053529 using compiled regex.Match/NextMatch
Found 1 matches in 00:00:00.0057524 using compiled regex.Match(String, Int32)&lt;/pre&gt;

&lt;p&gt;&lt;a href="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-30-50-metablogapi/5224.clip_5F00_image004_5F00_21B20492.gif"&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="clip_image004" border="0" alt="clip_image004" src="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-30-50-metablogapi/0246.clip_5F00_image004_5F00_thumb_5F00_3D569088.gif" width="632" height="249" /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you plan to call regular expression methods just a few times for a particular regular expression, or if the approximate number of calls to regular expression methods is unknown but is expected to be rather small, use interpreted regular expressions for best performance.&lt;/p&gt;

&lt;h2&gt;Compiled Regular Expressions&lt;/h2&gt;

&lt;p&gt;In contrast to interpreted regular expressions, compiled regular expressions increase startup time but execute individual pattern-matching methods faster. This means that the performance benefit that results from compiling the regular expression increases with the number of regular expression methods called. &lt;/p&gt;

&lt;p&gt;If the previous example, which opens a file that contains a single sentence, is replaced with an example that extracts each sentence from the entire text of Theodore Dreiser’s &lt;i&gt;The Financier&lt;/i&gt;, the performance benefit that results from compiling a regular expression becomes very clear. This variation of the example produces the following output, which shows that methods of compiled regular expressions execute about 30% faster than methods of interpreted regular expressions.&lt;/p&gt;

&lt;pre class="code"&gt;***Interpreted regular expressions***
Found 13679 matches in 00:00:01.9024852 using regex.Matches()
Found 13679 matches in 00:00:01.8579707 using regex.Match()/NextMatch()
Found 13679 matches in 00:00:01.8241908 using regex.Match(String, Int32)

***Compiled regular expressions***
Found 13679 matches in 00:00:01.1399927 using compiled regex.Matches()
Found 13679 matches in 00:00:01.1378395 using compiled regex.Match/NextMatch
Found 13679 matches in 00:00:01.1460928 using compiled regex.Match(String, Int32)&lt;/pre&gt;

&lt;p&gt;&lt;a href="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-30-50-metablogapi/3073.clip_5F00_image006_5F00_4F332455.gif"&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="clip_image006" border="0" alt="clip_image006" src="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-30-50-metablogapi/5125.clip_5F00_image006_5F00_thumb_5F00_610FB822.gif" width="655" height="305" /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;Static Interpreted and Compiled Regular Expressions&lt;/h2&gt;

&lt;p&gt;Just as instances of the &lt;b&gt;Regex&lt;/b&gt; class can be either compiled or interpreted, so can regular expressions used in static method calls. In interpreted static regular expressions, the internal regular expression opcodes are cached. In compiled static regular expressions, the MSIL is cached. As a result, compiled static regular expressions are faster than interpreted static regular expressions in cases in which methods are called repeatedly with the same regular expression. &lt;/p&gt;

&lt;p&gt;The previous two examples used a regular expression to extract sentences from a one-sentence string and from the complete text of Theodore Dreiser’s &lt;i&gt;The Financier&lt;/i&gt;. If we combine the two examples but replace the calls to instance &lt;b&gt;Regex&lt;/b&gt; methods with calls to the corresponding static methods, the following output results: &lt;/p&gt;

&lt;pre class="code"&gt;Reading file OneSentence.txt
***Interpreted regular expressions***
Found 1 matches in 00:00:00.0014642 using static Regex.Matches()
Found 1 matches in 00:00:00.0002807 using static Regex.Match()/NextMatch()

***Compiled regular expressions***
Found 1 matches in 00:00:00.0076935 using compiled static Regex.Matches()
Found 1 matches in 00:00:00.0089727 using compiled static Regex.Match/NextMatch

Reading file .\Dreiser_TheFinancier.txt
***Interpreted regular expressions***
Found 13679 matches in 00:00:02.1395809 using static Regex.Matches()
Found 13679 matches in 00:00:02.1683064 using static Regex.Match()/NextMatch()

***Compiled regular expressions***
Found 13679 matches in 00:00:01.2329685 using compiled static Regex.Matches()
Found 13679 matches in 00:00:01.1957317 using compiled static Regex.Match/NextMatch&lt;/pre&gt;

&lt;p&gt;This output shows the same relationship between interpreted and compiled static regular expressions that we observed for interpreted and compiled instance regular expressions. However, as the two charts that compare the performance of static and instance methods when making a single method call and when making multiple method calls to process a large block of text show, static regular expression methods offer performance that is generally inferior to instance regular expression methods. Their advantage lies in scenarios that use regular expression caching as an alternative to repeatedly re-instantiating the same regular expression object. &lt;/p&gt;

&lt;p&gt;&lt;a href="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-30-50-metablogapi/6204.clip_5F00_image008_5F00_4EC6F160.gif"&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="clip_image008" border="0" alt="clip_image008" src="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-30-50-metablogapi/8345.clip_5F00_image008_5F00_thumb_5F00_3C7E2A9E.gif" width="672" height="338" /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-30-50-metablogapi/3157.clip_5F00_image010_5F00_7C481123.gif"&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="clip_image010" border="0" alt="clip_image010" src="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-30-50-metablogapi/4456.clip_5F00_image010_5F00_thumb_5F00_3C11F7A9.gif" width="672" height="357" /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;Regular Expressions Compiled to an Assembly&lt;/h2&gt;

&lt;p&gt;The .NET Framework also allows you to create an assembly that contains compiled regular expressions. This moves the performance hit of regular expression compilation from runtime to design time. However, it also involves some additional work: You must define the regular expressions in advance and compile them to an assembly. The compiler can then reference this assembly when compiling source code that uses the assembly’s regular expressions.&lt;/p&gt;

&lt;p&gt;To compile regular expressions to an assembly, you call the &lt;b&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.compiletoassembly.aspx"&gt;Regex.CompileToAssembly&lt;/a&gt;&lt;/b&gt; method and pass it an array of &lt;b&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regexcompilationinfo.aspx"&gt;RegexCompilationInfo&lt;/a&gt;&lt;/b&gt; objects that represent the regular expressions to be compiled, and an &lt;b&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/system.reflection.assemblyname.aspx"&gt;AssemblyName&lt;/a&gt;&lt;/b&gt; object that contains information about the assembly to be created.&lt;/p&gt;

&lt;p&gt;For example, we can compile and store the regular expression that we’ve used to extract sentences from a string in a separate assembly. The following example does this:&lt;/p&gt;

&lt;pre class="code"&gt;[Visual Basic]
Imports System.Reflection
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim SentencePattern As New RegexCompilationInfo(&amp;quot;\b(\w+((\r?\n)|,?\s))*\w+[.?:;!]&amp;quot;,
                                                      RegexOptions.Multiline,
                                                      &amp;quot;SentencePattern&amp;quot;,
                                                      &amp;quot;Utilities.RegularExpressions&amp;quot;,
                                                      True)
      Dim regexes() As RegexCompilationInfo = {SentencePattern}
      Dim assemName As New AssemblyName(&amp;quot;RegexLib, Version=1.0.0.1001, Culture=neutral, PublicKeyToken=null&amp;quot;)
      Regex.CompileToAssembly(regexes, assemName)
   End Sub
End Module
[C#]
using System;
using System.Reflection;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      RegexCompilationInfo SentencePattern =
                           new RegexCompilationInfo(@&amp;quot;\b(\w+((\r?\n)|,?\s))*\w+[.?:;!]&amp;quot;,
                                                    RegexOptions.Multiline,
                                                    &amp;quot;SentencePattern&amp;quot;,
                                                    &amp;quot;Utilities.RegularExpressions&amp;quot;,
                                                    true);
      RegexCompilationInfo[] regexes = { SentencePattern };
      AssemblyName assemName = new AssemblyName(&amp;quot;RegexLib, Version=1.0.0.1001, Culture=neutral, PublicKeyToken=null&amp;quot;);
      Regex.CompileToAssembly(regexes, assemName);
   }
}&lt;/pre&gt;

&lt;p&gt;When the example is compiled to an executable and run, it creates an assembly named RegexLib.dll. The regular expression is represented by a class named &lt;b&gt;Utilities.RegularExpressions.SentencePattern&lt;/b&gt; that is derived from &lt;b&gt;Regex&lt;/b&gt;, as the following MSIL Disassembler (IL DASM) window illustrates. &lt;/p&gt;

&lt;p&gt;&lt;a href="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-30-50-metablogapi/6607.clip_5F00_image012_5F00_14D7AE74.jpg"&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="clip_image012" border="0" alt="clip_image012" src="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-30-50-metablogapi/5633.clip_5F00_image012_5F00_thumb_5F00_6D9D653E.jpg" width="676" height="181" /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;When you use this compiled regular expression to parse the text from the single-sentence file and from Theodore Dreiser’s &lt;i&gt;The Financier&lt;/i&gt;, the following output is displayed. Calls to the &lt;b&gt;SentencePattern&lt;/b&gt; pattern-matching methods produce execution times that are comparable to instance regular expressions that are called relatively few times, and to compiled regular expressions that are called repeatedly.&lt;/p&gt;

&lt;pre class="code"&gt;Reading file .\OneSentence.txt
***Regular expression compiled to an assembly***
Found 1 matches in 00:00:00.0062998 using Matches()
Found 1 matches in 00:00:00.0000396 using Match()/NextMatch()
Found 1 matches in 00:00:00.0000181 using Match(String, Int32)

Reading file .\Dreiser_TheFinancier.txt
***Regular expression compiled to an assembly***
Found 13679 matches in 00:00:01.1983633 using Matches()
Found 13679 matches in 00:00:01.1931376 using Match()/NextMatch()
Found 13679 matches in 00:00:01.1720003 using Match(String, Int32)&lt;/pre&gt;

&lt;p class="CodeCxSpFirst"&gt;&lt;span style="font-size: x-small"&gt;&lt;span style="font-family: courier new"&gt;&lt;st1:city w:st="on"&gt;&lt;st1:place w:st="on"&gt;&lt;/st1:place&gt;&lt;/st1:city&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;

&lt;p class="CodeCxSpLast"&gt;&lt;span style="font-size: x-small"&gt;&lt;span style="font-family: courier new"&gt;&lt;o:p&gt;&lt;/o:p&gt;&lt;/span&gt;&lt;/span&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-30-50-metablogapi/5618.clip_5F00_image014_5F00_74506EC1.gif"&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="clip_image014" border="0" alt="clip_image014" src="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-30-50-metablogapi/8863.clip_5F00_image014_5F00_thumb_5F00_1F28D2D4.gif" width="672" height="317" /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-30-50-metablogapi/0456.clip_5F00_image016_5F00_0CE00C12.gif"&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="clip_image016" border="0" alt="clip_image016" src="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-00-30-50-metablogapi/0250.clip_5F00_image016_5F00_thumb_5F00_13931595.gif" width="673" height="353" /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Regular expressions that are compiled to assemblies are typically considered less flexible than interpreted or compiled regular expressions. It is usually argued that they cannot support regular expressions that are built dynamically. Moreover, they are tightly coupled with the regular expression options that were provided to the regular expression’s &lt;b&gt;RegexCompilationInfo&lt;/b&gt; object. For example, the case sensitivity of a pattern match must be specified at the time the assembly is created; it cannot be defined by an argument supplied to a regular expression pattern-matching method. &lt;/p&gt;

&lt;p&gt;In fact, however, regular expressions can be compiled to an assembly dynamically, and regular expression objects can be defined dynamically as well. Although assemblies that contain compiled regular expressions are generally built separately from the application that uses them, this need not be the case. An assembly can be built dynamically by its application, the application can load the assembly dynamically by using reflection, and the regular expression object’s methods can also be called by using reflection. Note, however, that these techniques rely on reflection, which has a significant performance impact.&lt;/p&gt;

&lt;h2&gt;Best Practices for Regular Expression Object Usage&lt;/h2&gt;

&lt;p&gt;To maximize the performance of regular expressions in the .NET Framework, we recommend that you do the following when working with regular expression objects:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Call static regular expression matching methods instead of repeatedly instantiating the same regular expression object. &lt;/li&gt;

  &lt;li&gt;Use interpreted regular expressions when you expect to call pattern-matching methods a limited number of times to parse text. &lt;/li&gt;

  &lt;li&gt;Use compiled regular expressions to optimize performance for regular expression patterns that are known in advance and when the frequency of calls to the regular expression’s pattern-matching methods can vary extensively. &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Part II of this series will examine how you can improve regular expression performance by crafting regular expressions that limit excessive backtracking.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10013913" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/bclteam/archive/tags/RegEx/">RegEx</category></item><item><title>Code Contracts Survey</title><link>http://blogs.msdn.com/b/bclteam/archive/2010/05/24/code-contracts-survey.aspx</link><pubDate>Mon, 24 May 2010 22:38:06 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10014142</guid><dc:creator>BCL Team</dc:creator><slash:comments>5</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/bclteam/rsscomments.aspx?WeblogPostID=10014142</wfw:commentRss><comments>http://blogs.msdn.com/b/bclteam/archive/2010/05/24/code-contracts-survey.aspx#comments</comments><description>&lt;p&gt;The BCL Team has put together a survey about Code Contracts.&amp;nbsp; We're trying to get data about how people are using the feature to help us figure out where to invest in further development.&amp;nbsp; Even if you haven't used Code Contracts yet, your answers would be quite helpful.&amp;nbsp; We have a few questions to help us determine the main reasons people haven't tried the feature.&amp;nbsp; If you have a few minutes to spare, the survey can be found here: &lt;a href="http://codecontracts.questionpro.com/"&gt;http://codecontracts.questionpro.com&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Thanks in advance for your help.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10014142" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/bclteam/archive/tags/Contracts/">Contracts</category></item><item><title>Constructors and Value Types [Ron Petrusha]</title><link>http://blogs.msdn.com/b/bclteam/archive/2010/04/28/constructors-and-value-types-ron-petrusha.aspx</link><pubDate>Wed, 28 Apr 2010 20:50:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10004123</guid><dc:creator>BCL Team</dc:creator><slash:comments>7</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/bclteam/rsscomments.aspx?WeblogPostID=10004123</wfw:commentRss><comments>http://blogs.msdn.com/b/bclteam/archive/2010/04/28/constructors-and-value-types-ron-petrusha.aspx#comments</comments><description>&lt;P mce_keep="true"&gt;A number of recent customer comments have made it clear that some confusion surrounds the use of constructors with value types. Most common are the complaints that we've failed to document a constructor for a particular value type. In one case, though, a customer asked that we remove the documentation on constructors for value types, since he or she was certain that they are not supported by the .NET Framework. &lt;/P&gt;
&lt;P&gt;Just as you can define parameterized constructors for reference types, you can define parameterized constructors for value types. For example, the following code defines a &lt;B&gt;VehicleInfo&lt;/B&gt; structure that has two parameters: the number of wheels on a vehicle, and its number of doors. &lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt" class=Code&gt;&lt;FONT size=3&gt;&lt;FONT face="Courier New"&gt;[Visual Basic]&lt;?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" /&gt;&lt;o:p&gt;&lt;/o:p&gt;&lt;/FONT&gt;&lt;/FONT&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; COLOR: blue; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;Public&lt;/SPAN&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt; &lt;SPAN style="COLOR: blue"&gt;Structure&lt;/SPAN&gt; VehicleInfo&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;Private&lt;/SPAN&gt; nWheels &lt;SPAN style="COLOR: blue"&gt;As&lt;/SPAN&gt; &lt;SPAN style="COLOR: blue"&gt;Integer&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;Private&lt;/SPAN&gt; nDoors &lt;SPAN style="COLOR: blue"&gt;As&lt;/SPAN&gt; &lt;SPAN style="COLOR: blue"&gt;Integer&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; COLOR: blue; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;&lt;o:p&gt;&amp;nbsp;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;Public&lt;/SPAN&gt; &lt;SPAN style="COLOR: blue"&gt;Sub&lt;/SPAN&gt; &lt;SPAN style="COLOR: blue"&gt;New&lt;/SPAN&gt;(&lt;SPAN style="COLOR: blue"&gt;ByVal&lt;/SPAN&gt; wheels &lt;SPAN style="COLOR: blue"&gt;As&lt;/SPAN&gt; &lt;SPAN style="COLOR: blue"&gt;Integer&lt;/SPAN&gt;, &lt;SPAN style="COLOR: blue"&gt;ByVal&lt;/SPAN&gt; doors &lt;SPAN style="COLOR: blue"&gt;As&lt;/SPAN&gt; &lt;SPAN style="COLOR: blue"&gt;Integer&lt;/SPAN&gt;)&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;nWheels = wheels&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;nDoors = doors&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;End&lt;/SPAN&gt; &lt;SPAN style="COLOR: blue"&gt;Sub&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; COLOR: blue; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;&lt;o:p&gt;&amp;nbsp;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;Public&lt;/SPAN&gt; &lt;SPAN style="COLOR: blue"&gt;ReadOnly&lt;/SPAN&gt; &lt;SPAN style="COLOR: blue"&gt;Property&lt;/SPAN&gt; NumberOfWheels() &lt;SPAN style="COLOR: blue"&gt;As&lt;/SPAN&gt; &lt;SPAN style="COLOR: blue"&gt;Integer&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;Get&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;Return&lt;/SPAN&gt; nWheels&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;End&lt;/SPAN&gt; &lt;SPAN style="COLOR: blue"&gt;Get&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;End&lt;/SPAN&gt; &lt;SPAN style="COLOR: blue"&gt;Property&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; COLOR: blue; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;&lt;o:p&gt;&amp;nbsp;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;Public&lt;/SPAN&gt; &lt;SPAN style="COLOR: blue"&gt;ReadOnly&lt;/SPAN&gt; &lt;SPAN style="COLOR: blue"&gt;Property&lt;/SPAN&gt; Doors() &lt;SPAN style="COLOR: blue"&gt;As&lt;/SPAN&gt; &lt;SPAN style="COLOR: blue"&gt;Integer&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;Get&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;Return&lt;/SPAN&gt; nDoors&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;End&lt;/SPAN&gt; &lt;SPAN style="COLOR: blue"&gt;Get&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;End&lt;/SPAN&gt; &lt;SPAN style="COLOR: blue"&gt;Property&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; COLOR: blue; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;End&lt;/SPAN&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt; &lt;SPAN style="COLOR: blue"&gt;Structure&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt" class=Code&gt;&lt;FONT size=3&gt;&lt;FONT face="Courier New"&gt;&lt;/FONT&gt;&lt;/FONT&gt;&amp;nbsp;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt" class=Code&gt;&lt;FONT size=3&gt;&lt;FONT face="Courier New"&gt;[C#]&lt;o:p&gt;&lt;/o:p&gt;&lt;/FONT&gt;&lt;/FONT&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; COLOR: blue; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;using&lt;/SPAN&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt; System;&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;&lt;o:p&gt;&amp;nbsp;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; COLOR: blue; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;public&lt;/SPAN&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt; &lt;SPAN style="COLOR: blue"&gt;struct&lt;/SPAN&gt; &lt;SPAN style="COLOR: #2b91af"&gt;VehicleInfo&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;{&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;private&lt;/SPAN&gt; &lt;SPAN style="COLOR: blue"&gt;int&lt;/SPAN&gt; nWheels;&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;private&lt;/SPAN&gt; &lt;SPAN style="COLOR: blue"&gt;int&lt;/SPAN&gt; nDoors;&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;&lt;o:p&gt;&amp;nbsp;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;public&lt;/SPAN&gt; VehicleInfo(&lt;SPAN style="COLOR: blue"&gt;int&lt;/SPAN&gt; wheels, &lt;SPAN style="COLOR: blue"&gt;int&lt;/SPAN&gt; doors)&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;{&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;nWheels = wheels;&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;nDoors = doors;&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;}&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;&lt;o:p&gt;&amp;nbsp;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;public&lt;/SPAN&gt; &lt;SPAN style="COLOR: blue"&gt;int&lt;/SPAN&gt; NumberOfWheels&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;{&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;get&lt;/SPAN&gt; { &lt;SPAN style="COLOR: blue"&gt;return&lt;/SPAN&gt; nWheels; }&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;}&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;&lt;o:p&gt;&amp;nbsp;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;public&lt;/SPAN&gt; &lt;SPAN style="COLOR: blue"&gt;int&lt;/SPAN&gt; Doors&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;{&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;get&lt;/SPAN&gt; { &lt;SPAN style="COLOR: blue"&gt;return&lt;/SPAN&gt; nDoors; }&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;}&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt" class=Code&gt;&lt;SPAN style="FONT-SIZE: 10pt; mso-bidi-font-family: 'Courier New'; mso-bidi-language: HE; mso-no-proof: yes"&gt;&lt;FONT face="Courier New"&gt;}&lt;o:p&gt;&lt;/o:p&gt;&lt;/FONT&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P mce_keep="true"&gt;The example compiles normally, and when we use IL DASM to examine our type, we can see that it includes the parameterized constructor.&lt;/P&gt;
&lt;P mce_keep="true"&gt;&lt;IMG style="WIDTH: 589px; HEIGHT: 369px" title="Constructors and Value Types in ILDASM" border=0 alt="Constructors and Value Types in ILDASM" src="http://blogs.msdn.com/photos/bclteam/images/10004114/original.aspx" width=589 height=369 mce_src="http://blogs.msdn.com/photos/bclteam/images/10004114/original.aspx"&gt;&lt;/P&gt;
&lt;P mce_keep="true"&gt;So far, we haven't observed any differences between defining constructors for value types and defining them for reference types. However, this is where the similarity ends. While we can define a default or parameterless constructor for reference types, the attempt to define a default constructor for value types produces a compiler error. For example, if we modify the previous code by replacing the parameterized constructor with a default constructor and adding setters for the structure's two properties, the Visual Basic compiler displays the following error message:&lt;/P&gt;
&lt;BLOCKQUOTE&gt;
&lt;P style="MARGIN: 0in 0in 0pt" class=Code&gt;&lt;FONT size=3&gt;&lt;FONT face="Courier New"&gt;error BC30629: Structures cannot declare a non-shared 'Sub New' with no parameters.&lt;/FONT&gt;&lt;/FONT&gt;&lt;/P&gt;&lt;/BLOCKQUOTE&gt;
&lt;P style="MARGIN: 0in 0in 0pt" class=Code&gt;The equivalent C# code also fails to compile, with a slightly different error message:&lt;/P&gt;
&lt;BLOCKQUOTE&gt;
&lt;P style="MARGIN: 0in 0in 0pt" class=Code&gt;&lt;FONT size=3&gt;&lt;FONT face="Courier New"&gt;error CS0568: Structs cannot contain explicit parameterless constructors&lt;/FONT&gt;&lt;/FONT&gt;&lt;/P&gt;&lt;/BLOCKQUOTE&gt;
&lt;P style="MARGIN: 0in 0in 0pt" class=Code&gt;Not only can we not define a parameterless constructor for value types, but compilers don't supply one automatically if there is no defined constructor, as they do for reference types. For example, if we again modify our source code by deleting the parameterless constructor and then successfully compile, we can again use IL DASM to inspect the members of our type. As the following figure shows, a parameterless constructor is not a member of the structure.&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt" class=Code mce_keep="true"&gt;&amp;nbsp;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt" class=Code&gt;&lt;IMG style="WIDTH: 589px; HEIGHT: 369px" title="Constructors and Value Types in ILDASM" border=0 alt="Constructors and Value Types in ILDASM" src="http://blogs.msdn.com/photos/bclteam/images/10004115/original.aspx" width=589 height=369 mce_src="http://blogs.msdn.com/photos/bclteam/images/10004115/original.aspx"&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt" class=Code mce_keep="true"&gt;&amp;nbsp;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt" class=Code mce_keep="true"&gt;So to summarize, there are two major differences in the definition of constructors between value types and reference types:&lt;/P&gt;
&lt;UL&gt;
&lt;LI&gt;You can define a parameterless constructor for a reference type. You cannot define one for a value type.&lt;/LI&gt;
&lt;LI&gt;If you do not define any constructors, the compiler supplies a parameterless constructor for a reference type. It does not supply one for a value type.&lt;/LI&gt;&lt;/UL&gt;
&lt;P&gt;Given this, it may seem surprising that if we attempt to instantiate a &lt;B&gt;VehicleInfo&lt;/B&gt; object by calling its parameterless constructor, as the following example does, our code compiles successfully.&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt" class=Code&gt;&lt;FONT size=3&gt;&lt;FONT face="Courier New"&gt;[Visual Basic]&lt;o:p&gt;&lt;/o:p&gt;&lt;/FONT&gt;&lt;/FONT&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; COLOR: blue; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;Module&lt;/SPAN&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt; Example&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;Public&lt;/SPAN&gt; &lt;SPAN style="COLOR: blue"&gt;Sub&lt;/SPAN&gt; Main()&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;Dim&lt;/SPAN&gt; bicycle &lt;SPAN style="COLOR: blue"&gt;As&lt;/SPAN&gt; &lt;SPAN style="COLOR: blue"&gt;New&lt;/SPAN&gt; VehicleInfo()&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;bicycle.Doors = 0&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;bicycle.NumberOfWheels = 2&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;End&lt;/SPAN&gt; &lt;SPAN style="COLOR: blue"&gt;Sub&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt" class=Code&gt;&lt;FONT face="Courier New"&gt;&lt;SPAN style="COLOR: blue; FONT-SIZE: 10pt; mso-bidi-font-family: 'Courier New'; mso-bidi-language: HE; mso-no-proof: yes"&gt;End&lt;/SPAN&gt;&lt;SPAN style="FONT-SIZE: 10pt; mso-bidi-font-family: 'Courier New'; mso-bidi-language: HE; mso-no-proof: yes"&gt; &lt;SPAN style="COLOR: blue"&gt;Module&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/SPAN&gt;&lt;/FONT&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt" class=Code&gt;&lt;o:p&gt;&lt;FONT size=3 face="Courier New"&gt;&amp;nbsp;&lt;/FONT&gt;&lt;/o:p&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt" class=Code&gt;&lt;FONT size=3&gt;&lt;FONT face="Courier New"&gt;[C#]&lt;o:p&gt;&lt;/o:p&gt;&lt;/FONT&gt;&lt;/FONT&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; COLOR: blue; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;using&lt;/SPAN&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt; System;&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;&lt;o:p&gt;&amp;nbsp;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; COLOR: blue; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;public&lt;/SPAN&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt; &lt;SPAN style="COLOR: blue"&gt;class&lt;/SPAN&gt; &lt;SPAN style="COLOR: #2b91af"&gt;Example&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;{&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;public&lt;/SPAN&gt; &lt;SPAN style="COLOR: blue"&gt;static&lt;/SPAN&gt; &lt;SPAN style="COLOR: blue"&gt;void&lt;/SPAN&gt; Main()&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;{&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;&lt;SPAN style="COLOR: #2b91af"&gt;VehicleInfo&lt;/SPAN&gt; bicycle = &lt;SPAN style="COLOR: blue"&gt;new&lt;/SPAN&gt; &lt;SPAN style="COLOR: #2b91af"&gt;VehicleInfo&lt;/SPAN&gt;();&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;bicycle.Doors = 0;&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;bicycle.NumberOfWheels = 2;&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;}&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;}&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P mce_keep="true"&gt;On the one hand, no parameterless constructor exists in our &lt;B&gt;VehicleInfo&lt;/B&gt; type. On the other hand, we apparently are able to call this non-existent constructor. How can we explain this incongruous behavior?&lt;/P&gt;
&lt;P&gt;Let's begin by using IL DASM to examine the MSIL for a "normal" call to a parameterless constructor from a class. For the purpose of the example, we can define a class with no members named &lt;B&gt;TypicalClass&lt;/B&gt; and then instantiate it from another class that contains &lt;B&gt;Main&lt;/B&gt;, the application entry point. The following is the MSIL emitted by a Visual Basic compiler for the &lt;B&gt;Main&lt;/B&gt; method. Note the explicit call to the &lt;B&gt;TypicalClass&lt;/B&gt; default constructor. (A C# compiler also emits an identical call to the &lt;B&gt;TypicalClass&lt;/B&gt; default constructor.)&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: Fixedsys; FONT-SIZE: 10.5pt; mso-bidi-font-family: Fixedsys; mso-bidi-language: HE"&gt;.method public static void&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;&lt;?xml:namespace prefix = st1 ns = "urn:schemas-microsoft-com:office:smarttags" /&gt;&lt;st1:place w:st="on"&gt;Main&lt;/st1:place&gt;() cil managed&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: Fixedsys; FONT-SIZE: 10.5pt; mso-bidi-font-family: Fixedsys; mso-bidi-language: HE"&gt;{&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: Fixedsys; FONT-SIZE: 10.5pt; mso-bidi-font-family: Fixedsys; mso-bidi-language: HE"&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;.entrypoint&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: Fixedsys; FONT-SIZE: 10.5pt; mso-bidi-font-family: Fixedsys; mso-bidi-language: HE"&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;.custom instance void [mscorlib]System.STAThreadAttribute::.ctor() = ( 01 00 00 00 ) &lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: Fixedsys; FONT-SIZE: 10.5pt; mso-bidi-font-family: Fixedsys; mso-bidi-language: HE"&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;// Code size&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;7 (0x7)&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: Fixedsys; FONT-SIZE: 10.5pt; mso-bidi-font-family: Fixedsys; mso-bidi-language: HE"&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;.maxstack&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;1&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: Fixedsys; FONT-SIZE: 10.5pt; mso-bidi-font-family: Fixedsys; mso-bidi-language: HE"&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;.locals init (class TypicalClass V_0)&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: Fixedsys; FONT-SIZE: 10.5pt; mso-bidi-font-family: Fixedsys; mso-bidi-language: HE"&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;&lt;/SPAN&gt;&lt;SPAN style="FONT-FAMILY: Fixedsys; FONT-SIZE: 10.5pt; mso-bidi-font-family: Fixedsys; mso-bidi-language: HE; mso-ansi-language: FR" lang=FR&gt;IL_0000:&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;newobj&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;instance void TypicalClass::.ctor()&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: Fixedsys; FONT-SIZE: 10.5pt; mso-bidi-font-family: Fixedsys; mso-bidi-language: HE; mso-ansi-language: FR" lang=FR&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;IL_0005:&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;stloc.0&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: Fixedsys; FONT-SIZE: 10.5pt; mso-bidi-font-family: Fixedsys; mso-bidi-language: HE; mso-ansi-language: FR" lang=FR&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;&lt;/SPAN&gt;&lt;SPAN style="FONT-FAMILY: Fixedsys; FONT-SIZE: 10.5pt; mso-bidi-font-family: Fixedsys; mso-bidi-language: HE"&gt;IL_0006:&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;ret&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: Fixedsys; FONT-SIZE: 10.5pt; mso-bidi-font-family: Fixedsys; mso-bidi-language: HE"&gt;} // end of method Example::Main&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P mce_keep="true"&gt;We can then compare this with the IL generated by our call to the non-existent &lt;B&gt;VehicleInfo&lt;/B&gt; parameterless constructor. The following is the IL emitted by the C# compiler, although for our purposes the IL emitted by the Visual Basic compiler is identical.&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: Fixedsys; FONT-SIZE: 10.5pt; mso-bidi-font-family: Fixedsys; mso-bidi-language: HE"&gt;.method public hidebysig static void&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;&lt;st1:place w:st="on"&gt;Main&lt;/st1:place&gt;() cil managed&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: Fixedsys; FONT-SIZE: 10.5pt; mso-bidi-font-family: Fixedsys; mso-bidi-language: HE; mso-ansi-language: FR" lang=FR&gt;{&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: Fixedsys; FONT-SIZE: 10.5pt; mso-bidi-font-family: Fixedsys; mso-bidi-language: HE; mso-ansi-language: FR" lang=FR&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;.entrypoint&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: Fixedsys; FONT-SIZE: 10.5pt; mso-bidi-font-family: Fixedsys; mso-bidi-language: HE; mso-ansi-language: FR" lang=FR&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;// Code size&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;28 (0x1c)&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: Fixedsys; FONT-SIZE: 10.5pt; mso-bidi-font-family: Fixedsys; mso-bidi-language: HE; mso-ansi-language: FR" lang=FR&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;.maxstack&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;2&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: Fixedsys; FONT-SIZE: 10.5pt; mso-bidi-font-family: Fixedsys; mso-bidi-language: HE; mso-ansi-language: FR" lang=FR&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;.locals init (valuetype [NoConstructor1]VehicleInfo V_0)&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: Fixedsys; FONT-SIZE: 10.5pt; mso-bidi-font-family: Fixedsys; mso-bidi-language: HE; mso-ansi-language: FR" lang=FR&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;IL_0000:&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;nop&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: Fixedsys; FONT-SIZE: 10.5pt; mso-bidi-font-family: Fixedsys; mso-bidi-language: HE; mso-ansi-language: FR" lang=FR&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;IL_0001:&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;ldloca.s&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;V_0&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: Fixedsys; FONT-SIZE: 10.5pt; mso-bidi-font-family: Fixedsys; mso-bidi-language: HE; mso-ansi-language: FR" lang=FR&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;IL_0003:&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;initobj&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;[NoConstructor1]VehicleInfo&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: Fixedsys; FONT-SIZE: 10.5pt; mso-bidi-font-family: Fixedsys; mso-bidi-language: HE; mso-ansi-language: FR" lang=FR&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;IL_0009:&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;ldloca.s&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;V_0&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: Fixedsys; FONT-SIZE: 10.5pt; mso-bidi-font-family: Fixedsys; mso-bidi-language: HE; mso-ansi-language: FR" lang=FR&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;IL_000b:&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;ldc.i4.0&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: Fixedsys; FONT-SIZE: 10.5pt; mso-bidi-font-family: Fixedsys; mso-bidi-language: HE; mso-ansi-language: FR" lang=FR&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;IL_000c:&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;call&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;instance void [NoConstructor1]VehicleInfo::set_Doors(int32)&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: Fixedsys; FONT-SIZE: 10.5pt; mso-bidi-font-family: Fixedsys; mso-bidi-language: HE; mso-ansi-language: FR" lang=FR&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;IL_0011:&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;nop&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: Fixedsys; FONT-SIZE: 10.5pt; mso-bidi-font-family: Fixedsys; mso-bidi-language: HE; mso-ansi-language: FR" lang=FR&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;IL_0012:&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;ldloca.s&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;V_0&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: Fixedsys; FONT-SIZE: 10.5pt; mso-bidi-font-family: Fixedsys; mso-bidi-language: HE; mso-ansi-language: FR" lang=FR&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;IL_0014:&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;ldc.i4.2&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: Fixedsys; FONT-SIZE: 10.5pt; mso-bidi-font-family: Fixedsys; mso-bidi-language: HE; mso-ansi-language: FR" lang=FR&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;&lt;/SPAN&gt;&lt;SPAN style="FONT-FAMILY: Fixedsys; FONT-SIZE: 10.5pt; mso-bidi-font-family: Fixedsys; mso-bidi-language: HE"&gt;IL_0015:&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;call&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;instance void [NoConstructor1]VehicleInfo::set_NumberOfWheels(int32)&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: Fixedsys; FONT-SIZE: 10.5pt; mso-bidi-font-family: Fixedsys; mso-bidi-language: HE"&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;&lt;/SPAN&gt;&lt;SPAN style="FONT-FAMILY: Fixedsys; FONT-SIZE: 10.5pt; mso-bidi-font-family: Fixedsys; mso-bidi-language: HE; mso-ansi-language: FR" lang=FR&gt;IL_001a:&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;nop&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: Fixedsys; FONT-SIZE: 10.5pt; mso-bidi-font-family: Fixedsys; mso-bidi-language: HE; mso-ansi-language: FR" lang=FR&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;IL_001b:&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;ret&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: Fixedsys; FONT-SIZE: 10.5pt; mso-bidi-font-family: Fixedsys; mso-bidi-language: HE"&gt;} // end of method Example::Main&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P mce_keep="true"&gt;The call to the non-existent parameterless constructor in our source code has been replaced by a call to &lt;B&gt;Initobj&lt;/B&gt;, an MSIL opcode that is documented at &lt;A href="http://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.initobj(VS.100).aspx"&gt;http://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.initobj(VS.100).aspx&lt;/A&gt;. &lt;B&gt;Initobj&lt;/B&gt; initializes each field in a value type to its default value. &lt;/P&gt;
&lt;P&gt;This feature - the ability to instantiate a value type by using a language's constructor syntax to invoke a default value type even though one does not exist -- is known as the &lt;I&gt;implicit default constructor&lt;/I&gt;. In C# in particular, it is necessary to use the implicit default constructor to instantiate value types that do not define parameterized constructors, since otherwise the C# compiler generates error CS0165: "Use of unassigned local variable 'bicycle'", because C# does not allow variables to be used before they're explicitly initialized.&lt;/P&gt;
&lt;P&gt;On the other hand, Visual Basic does not&amp;nbsp; forbid the use of unassigned value types, since it provides a call to the implicit default constructor if none is present in source code. For example, the following Visual Basic code is similar to the previous example, except that it omits the call to the &lt;B&gt;VehicleInfo&lt;/B&gt; default constructor. &lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt" class=Code&gt;&lt;FONT size=3&gt;&lt;FONT face="Courier New"&gt;[Visual Basic]&lt;o:p&gt;&lt;/o:p&gt;&lt;/FONT&gt;&lt;/FONT&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; COLOR: blue; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;Module&lt;/SPAN&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt; Example&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;Public&lt;/SPAN&gt; &lt;SPAN style="COLOR: blue"&gt;Sub&lt;/SPAN&gt; Main()&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;Dim&lt;/SPAN&gt; bicycle &lt;SPAN style="COLOR: blue"&gt;As&lt;/SPAN&gt; VehicleInfo&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;bicycle.Doors = 0&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;bicycle.NumberOfWheels = 2&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: 'Courier New'; FONT-SIZE: 10pt; mso-bidi-language: HE; mso-no-proof: yes"&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;&lt;SPAN style="COLOR: blue"&gt;End&lt;/SPAN&gt; &lt;SPAN style="COLOR: blue"&gt;Sub&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt" class=Code&gt;&lt;FONT face="Courier New"&gt;&lt;SPAN style="COLOR: blue; FONT-SIZE: 10pt; mso-bidi-font-family: 'Courier New'; mso-bidi-language: HE; mso-no-proof: yes"&gt;End&lt;/SPAN&gt;&lt;SPAN style="FONT-SIZE: 10pt; mso-bidi-font-family: 'Courier New'; mso-bidi-language: HE; mso-no-proof: yes"&gt; &lt;SPAN style="COLOR: blue"&gt;Module&lt;/SPAN&gt;&lt;/SPAN&gt;&lt;/FONT&gt;&lt;o:p&gt;&lt;/o:p&gt;&lt;/P&gt;
&lt;P mce_keep="true"&gt;The following is the MSIL emitted by a Visual Basic compiler for this version of the &lt;B&gt;Main&lt;/B&gt; method.&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: Fixedsys; FONT-SIZE: 10.5pt; mso-bidi-font-family: Fixedsys; mso-bidi-language: HE"&gt;.method public static void&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;&lt;st1:place w:st="on"&gt;Main&lt;/st1:place&gt;() cil managed&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: Fixedsys; FONT-SIZE: 10.5pt; mso-bidi-font-family: Fixedsys; mso-bidi-language: HE"&gt;{&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: Fixedsys; FONT-SIZE: 10.5pt; mso-bidi-font-family: Fixedsys; mso-bidi-language: HE"&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;.entrypoint&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: Fixedsys; FONT-SIZE: 10.5pt; mso-bidi-font-family: Fixedsys; mso-bidi-language: HE"&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;.custom instance void [mscorlib]System.STAThreadAttribute::.ctor() = ( 01 00 00 00 ) &lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: Fixedsys; FONT-SIZE: 10.5pt; mso-bidi-font-family: Fixedsys; mso-bidi-language: HE"&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;&lt;/SPAN&gt;&lt;SPAN style="FONT-FAMILY: Fixedsys; FONT-SIZE: 10.5pt; mso-bidi-font-family: Fixedsys; mso-bidi-language: HE; mso-ansi-language: FR" lang=FR&gt;// Code size&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;17 (0x11)&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: Fixedsys; FONT-SIZE: 10.5pt; mso-bidi-font-family: Fixedsys; mso-bidi-language: HE; mso-ansi-language: FR" lang=FR&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;.maxstack&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;2&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: Fixedsys; FONT-SIZE: 10.5pt; mso-bidi-font-family: Fixedsys; mso-bidi-language: HE; mso-ansi-language: FR" lang=FR&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;.locals init (valuetype [NoConstructor1]VehicleInfo V_0)&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: Fixedsys; FONT-SIZE: 10.5pt; mso-bidi-font-family: Fixedsys; mso-bidi-language: HE; mso-ansi-language: FR" lang=FR&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;IL_0000:&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;ldloca.s&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;V_0&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: Fixedsys; FONT-SIZE: 10.5pt; mso-bidi-font-family: Fixedsys; mso-bidi-language: HE; mso-ansi-language: FR" lang=FR&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;IL_0002:&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;ldc.i4.0&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: Fixedsys; FONT-SIZE: 10.5pt; mso-bidi-font-family: Fixedsys; mso-bidi-language: HE; mso-ansi-language: FR" lang=FR&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;&lt;/SPAN&gt;&lt;SPAN style="FONT-FAMILY: Fixedsys; FONT-SIZE: 10.5pt; mso-bidi-font-family: Fixedsys; mso-bidi-language: HE"&gt;IL_0003:&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;call&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;instance void [NoConstructor1]VehicleInfo::set_Doors(int32)&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: Fixedsys; FONT-SIZE: 10.5pt; mso-bidi-font-family: Fixedsys; mso-bidi-language: HE"&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;&lt;/SPAN&gt;&lt;SPAN style="FONT-FAMILY: Fixedsys; FONT-SIZE: 10.5pt; mso-bidi-font-family: Fixedsys; mso-bidi-language: HE; mso-ansi-language: FR" lang=FR&gt;IL_0008:&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;ldloca.s&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;V_0&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: Fixedsys; FONT-SIZE: 10.5pt; mso-bidi-font-family: Fixedsys; mso-bidi-language: HE; mso-ansi-language: FR" lang=FR&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;IL_000a:&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;ldc.i4.2&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: Fixedsys; FONT-SIZE: 10.5pt; mso-bidi-font-family: Fixedsys; mso-bidi-language: HE; mso-ansi-language: FR" lang=FR&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;&lt;/SPAN&gt;&lt;SPAN style="FONT-FAMILY: Fixedsys; FONT-SIZE: 10.5pt; mso-bidi-font-family: Fixedsys; mso-bidi-language: HE"&gt;IL_000b:&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;call&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/SPAN&gt;instance void [NoConstructor1]VehicleInfo::set_NumberOfWheels(int32)&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: Fixedsys; FONT-SIZE: 10.5pt; mso-bidi-font-family: Fixedsys; mso-bidi-language: HE"&gt;&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;IL_0010:&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;ret&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 0pt; mso-layout-grid-align: none" class=MsoNormal&gt;&lt;SPAN style="FONT-FAMILY: Fixedsys; FONT-SIZE: 10.5pt; mso-bidi-font-family: Fixedsys; mso-bidi-language: HE"&gt;} // end of method Example::Main&lt;o:p&gt;&lt;/o:p&gt;&lt;/SPAN&gt;&lt;/P&gt;
&lt;P mce_keep="true"&gt;In this case, the &lt;B&gt;Initobj&lt;/B&gt; opcode has been replaced by &lt;B&gt;init&lt;/B&gt;, but the result is the same: each field of a value type is initialized to its default value. In Visual Basic, an implicit default constructor is invoked whether or not that constructor is actually used in source code.&lt;/P&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10004123" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/bclteam/archive/tags/ValueType/">ValueType</category><category domain="http://blogs.msdn.com/b/bclteam/archive/tags/Constructors/">Constructors</category></item><item><title>BCL CodePlex Site Launch</title><link>http://blogs.msdn.com/b/bclteam/archive/2010/03/30/bcl-codeplex-site-launch.aspx</link><pubDate>Tue, 30 Mar 2010 21:03:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9987688</guid><dc:creator>BCL Team</dc:creator><slash:comments>8</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/bclteam/rsscomments.aspx?WeblogPostID=9987688</wfw:commentRss><comments>http://blogs.msdn.com/b/bclteam/archive/2010/03/30/bcl-codeplex-site-launch.aspx#comments</comments><description>&lt;P style="MARGIN: 0in 0in 10pt" class=MsoNormal&gt;&lt;FONT size=3 face=Calibri&gt;Today the BCL Team is launching a &lt;/FONT&gt;&lt;A href="http://www.codeplex.com/"&gt;&lt;FONT size=3 face=Calibri&gt;CodePlex&lt;/FONT&gt;&lt;/A&gt;&lt;FONT size=3 face=Calibri&gt; site to host samples, previews, and prototypes.&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;You can find it at &lt;/FONT&gt;&lt;A href="http://bcl.codeplex.com/"&gt;&lt;FONT size=3 face=Calibri&gt;http://bcl.codeplex.com&lt;/FONT&gt;&lt;/A&gt;&lt;FONT size=3&gt;&lt;FONT face=Calibri&gt;. &lt;BR&gt;&lt;BR&gt;This is a site for the BCL Team to get features to customers to try out without requiring a Beta or CTP of the .NET Framework. &lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&lt;/SPAN&gt;Our goal is to put generally useful functionality on the CodePlex site, and to get feedback on it and have the chance to iterate on the design. &lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&lt;/SPAN&gt;Having a feature there does &lt;B&gt;not&lt;/B&gt; mean that it will eventually end up in the BCL. &lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp;&lt;/SPAN&gt;Some items are samples that build on top of existing classes, and some features might be ones we were considering for the .NET Framework but decided not to include for one reason or another.&lt;BR&gt;&lt;BR&gt;We'd love to get your feedback in the form of comments, bug reports, and feature requests, but please note that we cannot take code submissions. We plan to release updates with new features and updates to existing features on a quarterly basis, but we're just getting started with this and may adjust our schedule depending on how things go.&lt;BR&gt;&lt;BR&gt;And just to avoid confusion, you will &lt;B&gt;not&lt;/B&gt; find the source code for the whole BCL on this CodePlex site. The site is for things we're thinking about for the future, not our existing classes.&lt;?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" /&gt;&lt;o:p&gt;&lt;/o:p&gt;&lt;/FONT&gt;&lt;/FONT&gt;&lt;/P&gt;
&lt;P style="MARGIN: 0in 0in 10pt" class=MsoNormal&gt;&lt;FONT size=3&gt;&lt;FONT face=Calibri&gt;The first four projects up on the site are BigRational, Long Path, PerfMonitor, and TraceEvent.&lt;SPAN style="mso-spacerun: yes"&gt;&amp;nbsp; &lt;/SPAN&gt;Go check them out and let us know what you think.&lt;o:p&gt;&lt;/o:p&gt;&lt;/FONT&gt;&lt;/FONT&gt;&lt;/P&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9987688" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/bclteam/archive/tags/News/">News</category><category domain="http://blogs.msdn.com/b/bclteam/archive/tags/-NET+Framework+4/">.NET Framework 4</category><category domain="http://blogs.msdn.com/b/bclteam/archive/tags/CodePlex/">CodePlex</category></item><item><title>I just installed Visual Studio 2010, now how do I get Code Contracts? [Melitta Andersen]</title><link>http://blogs.msdn.com/b/bclteam/archive/2010/01/26/i-just-installed-visual-studio-2010-now-how-do-i-get-code-contracts-melitta-andersen.aspx</link><pubDate>Wed, 27 Jan 2010 00:57:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9953806</guid><dc:creator>BCL Team</dc:creator><slash:comments>3</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/bclteam/rsscomments.aspx?WeblogPostID=9953806</wfw:commentRss><comments>http://blogs.msdn.com/b/bclteam/archive/2010/01/26/i-just-installed-visual-studio-2010-now-how-do-i-get-code-contracts-melitta-andersen.aspx#comments</comments><description>&lt;P&gt;This article is to show you how to go from a clean install of Visual Studio 2010 to running the Code Contract tools for the first time.&amp;nbsp; Since the tools aren’t included in VS install, we thought we’d provide some extra information on where to find them.&amp;nbsp; If you’re already using Code Contracts in Visual Studio 2010, this blog post probably won’t have anything new for you.&amp;nbsp; If you want an overview of the System.Diagnostics.Contracts.Contract class, please see &lt;A href="http://blogs.msdn.com/bclteam/archive/tags/Contracts/default.aspx" mce_href="http://blogs.msdn.com/bclteam/archive/tags/Contracts/default.aspx"&gt;earlier blog posts&lt;/A&gt; or &lt;A href="http://msdn.microsoft.com/en-us/library/system.diagnostics.contracts.contract(VS.100).aspx" mce_href="http://msdn.microsoft.com/en-us/library/system.diagnostics.contracts.contract(VS.100).aspx"&gt;documentation&lt;/A&gt;.&amp;nbsp; This post is just about getting set up for the very first time.&lt;/P&gt;
&lt;P&gt;This article might also be useful to you if you’ve tried to run a project and gotten an assert stating that “This assembly must be rewritten using the binary rewriter.”&amp;nbsp; That can happen if you’ve used certain methods on the System.Diagnostics.Contracts.Contract class in your code and defined the appropriate symbol to have them compiled into your code, but haven’t run the tools mentioned here.&lt;/P&gt;
&lt;P&gt;If you want the really quick version of this post, the answer is to go download the appropriate installer linked to on the right side of this page: &lt;A href="http://msdn.microsoft.com/en-us/devlabs/dd491992.aspx" mce_href="http://msdn.microsoft.com/en-us/devlabs/dd491992.aspx"&gt;http://msdn.microsoft.com/en-us/devlabs/dd491992.aspx&lt;/A&gt;. Then use the Code Contracts pane in the Properties of your project to perform runtime contract checking.&amp;nbsp; Without this setting, contracts are not checked - we don’t compile them into your code without this option.&amp;nbsp; If you want a few more details, read on.&lt;/P&gt;
&lt;P&gt;The Contract class is included in the Microsoft .NET Framework 4, but the tools that take advantage of them are found on &lt;A href="http://msdn.microsoft.com/en-us/devlabs/default.aspx" mce_href="http://msdn.microsoft.com/en-us/devlabs/default.aspx"&gt;DevLabs&lt;/A&gt; (more on that later).&amp;nbsp; There are two primary tools: ccrewrite.exe, a binary rewriter that moves your contracts to the correct place in the code and checks whether the contracts are written correctly, and cccheck.exe, a static analysis tool that will find places where contracts have been violated without running your code.&amp;nbsp; Think of cccheck like FxCop for finding bugs, using the rules you establish via your own contracts.&amp;nbsp; You cannot do runtime checking of your contracts without using ccrewrite.exe.&amp;nbsp; Because of this, most of the methods on the Contract class are conditionally compiled, which means that calls to them won’t be included in your code without a special symbol being defined.&amp;nbsp; The tools provide an easy way to define that symbol in a new tab on the properties pane of your project and run ccrewrite immediately after compiling your assemblies.&lt;/P&gt;
&lt;H3&gt;Downloading from DevLabs&lt;/H3&gt;
&lt;P&gt;&lt;A href="http://msdn.microsoft.com/en-us/devlabs/default.aspx" mce_href="http://msdn.microsoft.com/en-us/devlabs/default.aspx"&gt;DevLabs&lt;/A&gt; is a Microsoft site for sharing prototypes of tools for developers and getting feedback on them from the community.&amp;nbsp; The Code Contract tools started out as a project in Microsoft Research.&amp;nbsp; We’re working on getting them incorporated into products, but to get them out where our customers can use them in this release, we’re hosting them on DevLabs.&amp;nbsp; In addition to being a place to host the tools, the &lt;A href="http://msdn.microsoft.com/en-us/devlabs/dd491992.aspx" mce_href="http://msdn.microsoft.com/en-us/devlabs/dd491992.aspx"&gt;Code Contracts&lt;/A&gt; page also has a &lt;A href="http://social.msdn.microsoft.com/Forums/en-US/codecontracts/threads/" mce_href="http://social.msdn.microsoft.com/Forums/en-US/codecontracts/threads/"&gt;forum&lt;/A&gt;, &lt;A href="http://research.microsoft.com/en-us/projects/contracts/faq.aspx" mce_href="http://research.microsoft.com/en-us/projects/contracts/faq.aspx"&gt;FAQ&lt;/A&gt;, and &lt;A href="http://download.microsoft.com/download/C/2/7/C2715F76-F56C-4D37-9231-EF8076B7EC13/userdoc.pdf" mce_href="http://download.microsoft.com/download/C/2/7/C2715F76-F56C-4D37-9231-EF8076B7EC13/userdoc.pdf"&gt;documentation&lt;/A&gt; for the tools.&lt;/P&gt;
&lt;P&gt;There are two different installers for the Code Contracts tools.&amp;nbsp; The one that includes the static checker requires VS 2010 Premium or VS 2010 Ultimate.&amp;nbsp; The version without the static checker will work on any edition of VS 2010 other than the Express Edition, and is what the DevLabs site refers to (for now) as the “Standard Edition” of the tools.&amp;nbsp; Pick which version works for you, and you’ll get the usual prompt asking if you want to run or save the file.&lt;/P&gt;
&lt;P align=center&gt;&lt;A href="http://msdn.microsoft.com/en-us/devlabs/dd491992.aspx" mce_href="http://msdn.microsoft.com/en-us/devlabs/dd491992.aspx"&gt;&lt;IMG border=0 alt="Code Contracts on DevLabs" src="http://blogs.msdn.com/photos/bclteam/images/9953796/original.aspx" width=624 height=658 mce_src="http://blogs.msdn.com/photos/bclteam/images/9953796/original.aspx"&gt;&lt;/A&gt;&lt;/P&gt;
&lt;H3&gt;Enabling Contracts in Projects&lt;/H3&gt;
&lt;P&gt;The installer adds a tab to the properties pane for projects in Visual Studio.&amp;nbsp; It has quite a few options that are described in the aforementioned &lt;A href="http://download.microsoft.com/download/C/2/7/C2715F76-F56C-4D37-9231-EF8076B7EC13/userdoc.pdf" mce_href="http://download.microsoft.com/download/C/2/7/C2715F76-F56C-4D37-9231-EF8076B7EC13/userdoc.pdf"&gt;documentation&lt;/A&gt; for the tools.&amp;nbsp; The two most important, though, are the checkboxes to Perform Runtime Contract Checking and (if you have the static checker) to Perform Static Contract Checking.&amp;nbsp; The option to perform runtime checking will define the symbol to put contracts in your code and enable a post-build step to put the checks for those contracts in the correct place (for instance, placing checks for post-conditions at every exit of a method).&amp;nbsp;&amp;nbsp; If those contracts are violated, an assertion or exception will happen, depending on your selections for the other options on the tab.&amp;nbsp; If you enable static contract checking, cccheck.exe will run in the background to try to prove all of the contracts you have written in your code.&lt;/P&gt;
&lt;P align=center&gt;&lt;IMG border=0 alt="Code Contracts in Visual Studio 2010" src="http://blogs.msdn.com/photos/bclteam/images/9953797/original.aspx" width=624 height=411 mce_src="http://blogs.msdn.com/photos/bclteam/images/9953797/original.aspx"&gt;&lt;/P&gt;
&lt;P&gt;I hope this helps you to get started using Code Contracts.&amp;nbsp; If you’re just getting started with the feature, I strongly encourage you to spend some time on the &lt;A href="http://social.msdn.microsoft.com/Forums/en-US/codecontracts/threads/" mce_href="http://social.msdn.microsoft.com/Forums/en-US/codecontracts/threads/"&gt;forum&lt;/A&gt; or reading the &lt;A href="http://msdn.microsoft.com/en-us/library/system.diagnostics.contracts.contract(VS.100).aspx" mce_href="http://msdn.microsoft.com/en-us/library/system.diagnostics.contracts.contract(VS.100).aspx"&gt;documentation&lt;/A&gt; on MSDN.&lt;/P&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9953806" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/bclteam/archive/tags/-NET+Framework+4/">.NET Framework 4</category><category domain="http://blogs.msdn.com/b/bclteam/archive/tags/Contracts/">Contracts</category></item></channel></rss>
