<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:base="https://illuminatedcomputing.com/">
  <id>https://illuminatedcomputing.com/</id>
  <title>Illuminated Computing</title>
  <updated>2011-02-12T00:00:00Z</updated>
  <link rel="alternate" href="https://illuminatedcomputing.com/" type="text/html"/>
  <link rel="self" href="https://illuminatedcomputing.com/tags/c-sharp/atom.xml" type="application/atom+xml"/>
  <author>
    <name>Paul A. Jungwirth</name>
    <uri>https://illuminatedcommputing.com/</uri>
  </author>
  <entry>
    <id>tag:illuminatedcomputing.com,2011-02-12:/posts/2011/02/visual-studio-unit-tests-with-resources/</id>
    <title type="html">Visual Studio Unit Tests with Resources</title>
    <published>2011-02-12T00:00:00Z</published>
    <updated>2011-02-12T00:00:00Z</updated>
    <link rel="alternate" href="https://illuminatedcomputing.com/posts/2011/02/visual-studio-unit-tests-with-resources/" type="text/html"/>
    <content type="html">
&lt;p&gt;I have a project that needs to load a lot of historical data from a JSON file to support various computations. This is a Windows Forms app built in C# using Visual Studio 2008. In the application, I can open the JSON file like this:&lt;/p&gt;

&lt;div class="CodeRay"&gt;&lt;div class="code"&gt;&lt;pre&gt;&lt;code class="language-csharp"&gt;string json = File.ReadAllText(Path.Combine(Application.StartupPath, "figures.json"));&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;But I also want to write unit tests against the parts of the app that need this file. I’m using Visual Studio’s built-in unit test framework. I was trying to figure out how to ensure the unit test can get access to the file. It turns out, I just add this annotation to any test method that needs the file:&lt;/p&gt;

&lt;div class="CodeRay"&gt;&lt;div class="code"&gt;&lt;pre&gt;&lt;code class="language-csharp"&gt;[DeploymentItem("figures.json")]&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Then I can open the file like this:&lt;/p&gt;

&lt;div class="CodeRay"&gt;&lt;div class="code"&gt;&lt;pre&gt;&lt;code class="language-csharp"&gt;string json = File.ReadAllText(Path.Combine(testContextInstance.TestDeploymentDir, "figures.json"));&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;I can also put the annotation on the test class, rather than tagging each separate method. Unfortunately I can’t apply it to the whole test assembly. I was hoping I could stick it in AssemblyInfo.cs, but then I get an error that it only works on classes and methods. Oh well!&lt;/p&gt;
</content>
  </entry>
  <entry>
    <id>tag:illuminatedcomputing.com,2011-01-23:/posts/2011/01/c-access-modifiers-and-unit-tests/</id>
    <title type="html">C# Access Modifiers and Unit Tests</title>
    <published>2011-01-23T00:00:00Z</published>
    <updated>2011-01-23T00:00:00Z</updated>
    <link rel="alternate" href="https://illuminatedcomputing.com/posts/2011/01/c-access-modifiers-and-unit-tests/" type="text/html"/>
    <content type="html">
&lt;p&gt;Access modifiers (&lt;code&gt;public&lt;/code&gt;, &lt;code&gt;private&lt;/code&gt;, &lt;code&gt;protected&lt;/code&gt;, &lt;code&gt;internal&lt;/code&gt;) for C++, Java, and C# were designed before unit testing really became popular, and it’s hard to write unit tests against non-public methods. I like the pattern of putting all tests into a separate package/assembly, so you can easily separate them from a production build. You can also use naming conventions, but that seems less robust. When I’ve tried that approach, inevitably some support classes for tests, like mock objects, leaked into the production release. That can be dangerous. But if you put your tests into a separate assembly, how do you test non-public methods?&lt;/p&gt;

&lt;p&gt;Some people say you shouldn’t test non-public methods, but that sounds to me like coder religion. Why not? I find it very useful, when separating a big method into helper methods, to test the helper methods individually so I know they’re right. If the code is complex enough to warrant a helper method, it may be complex enough to warrant a test. I’ve been writing a lot of financial computation code lately, and that’s the kind of thing you need to get right. I’ve never been so diligent about writing unit tests as now. It’s quite handy to test units smaller than public method calls. So how do you do it?&lt;/p&gt;

&lt;p&gt;One solution is to mark everything as &lt;code&gt;public&lt;/code&gt;. I confess this actually appeals a little to my practical side. As long as you’re not building a truly public API (and few business programmers are), it’s okay to leave helper methods as public. It’s easy to spend unnecessary time thinking about &lt;code&gt;public&lt;/code&gt; vs. &lt;code&gt;private&lt;/code&gt;, and inevitably you wind up too strict somewhere so you waste time going back and changing things.&lt;/p&gt;

&lt;p&gt;But ultimately I prefer to keep helper methods private. It is self-documenting. When you read someone else’s code (including month-ago you), it’s a relief to know that some methods are never called from outside the class. It helps you understand a method’s intent if &lt;code&gt;public&lt;/code&gt; and &lt;code&gt;private&lt;/code&gt; mean something. Isolating the true public methods can substantially lighten the complexity burden of understanding how a class works. Also, a private method doesn’t need its inputs sanitized quite so rigorously. And with Visual Studio, keeping helper methods private improves IntelliSense, if you use that. So I want to take advantage of &lt;code&gt;private&lt;/code&gt; and friends, if I can make it work with unit testing.&lt;/p&gt;

&lt;p&gt;Fortunately, C# offers a way to do this. In Properties/AssemblyInfo.cs, you can add a line like this:&lt;/p&gt;

&lt;div class="CodeRay"&gt;&lt;div class="code"&gt;&lt;pre&gt;&lt;code class="language-csharp"&gt;[assembly:InternalsVisibleTo("FooTests")]&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;Then, whatever methods you mark &lt;code&gt;internal&lt;/code&gt; are accessible to your test project. (Remember that &lt;code&gt;internal&lt;/code&gt; allows access from anywhere in the same assembly.) Sadly this attribute doesn’t open up &lt;code&gt;private&lt;/code&gt; methods, but if your development group knows that &lt;code&gt;internal&lt;/code&gt; is basically synonymous with &lt;code&gt;private&lt;/code&gt;, it’s not a bad compromise. It still lets you distinguish between the public API and everything else. I like this approach a lot.&lt;/p&gt;
</content>
  </entry>
  <entry>
    <id>tag:illuminatedcomputing.com,2010-07-26:/posts/2010/07/c-new-vs-override/</id>
    <title type="html">c# new vs. override</title>
    <published>2010-07-26T00:00:00Z</published>
    <updated>2010-07-26T00:00:00Z</updated>
    <link rel="alternate" href="https://illuminatedcomputing.com/posts/2010/07/c-new-vs-override/" type="text/html"/>
    <content type="html">
&lt;p&gt;C# has two keywords for decorating methods, &lt;code&gt;new&lt;/code&gt; and &lt;code&gt;override&lt;/code&gt;, that have almost identical effects.&lt;/p&gt;
&lt;emph&gt;Almost&lt;/emph&gt;
&lt;p&gt;. They are both used to override a method on a base class, but how do they differ? A lot of documentation I’ve read is pretty vague, saying something like, “Overriding a virtual method with the &lt;code&gt;new&lt;/code&gt; keyword hides, rather than overrides, the base class implementation of the method.” Here is what that means:&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;override&lt;/code&gt; keyword creates a true run-time method override, whereas the &lt;code&gt;new&lt;/code&gt; keyword affects only compile-time method identification. This is a bit like the difference between overriding and overloading. So if your object is declared as &lt;code&gt;Animal&lt;/code&gt; but you’ve really got a &lt;code&gt;Dog&lt;/code&gt;, calling a method with &lt;code&gt;override&lt;/code&gt; will execute the &lt;code&gt;Dog&lt;/code&gt; implementation, but calling a method with &lt;code&gt;new&lt;/code&gt; will execute the &lt;code&gt;Animal&lt;/code&gt; implementation, because that’s all the compiler can see.&lt;/p&gt;

&lt;p&gt;If you have a C++ background, you can think of this in terms of a virtual method table or dispatch table. In C#, only methods marked &lt;code&gt;virtual&lt;/code&gt; get such a table. The &lt;code&gt;override&lt;/code&gt; keyword adds a new entry to that table, whereas &lt;code&gt;new&lt;/code&gt; does not.&lt;/p&gt;

&lt;p&gt;C# is more conservative than Java when it comes to method overrides. In Java, by default you can override any method, after accounting for the usual access modifiers (&lt;code&gt;public&lt;/code&gt;/&lt;code&gt;protected&lt;/code&gt;/&lt;code&gt;private&lt;/code&gt;). This led to problems where subclasses could break functionality by overriding methods the base class didn’t expect. In C#, you can only override those methods the base class explicitly permits. So you can only use &lt;code&gt;override&lt;/code&gt; if the base class method is marked &lt;code&gt;virtual&lt;/code&gt;. However, you can use &lt;code&gt;new&lt;/code&gt; on any method. As long as the compile-time type of an object is the subclass, your &lt;code&gt;new&lt;/code&gt; method will be called, but the base method will continue to be called elsewhere, including (most importantly) from within the base class.&lt;/p&gt;
</content>
  </entry>
  <entry>
    <id>tag:illuminatedcomputing.com,2010-03-16:/posts/2010/03/a-linq-catalog/</id>
    <title type="html">A Linq Catalog</title>
    <published>2010-03-16T00:00:00Z</published>
    <updated>2010-03-16T00:00:00Z</updated>
    <link rel="alternate" href="https://illuminatedcomputing.com/posts/2010/03/a-linq-catalog/" type="text/html"/>
    <content type="html">
&lt;p&gt;I thought I’d review the special methods available in Linq. In the API reference, they can be found under the &lt;code&gt;Enumerable&amp;lt;T&amp;gt;&lt;/code&gt; class. Here they are:&lt;/p&gt;

&lt;div class="CodeRay"&gt;&lt;div class="code"&gt;&lt;pre&gt;&lt;code class="language-csharp"&gt;static IEnumerable&amp;lt;T&amp;gt; Empty&amp;lt;T&amp;gt;()
static IEnumerable&amp;lt;T&amp;gt; Repeat&amp;lt;T&amp;gt;(T element, int count)



T[] ToArray()
List&amp;lt;T&amp;gt; ToList()
Dictionary&amp;lt;K,T&amp;gt; ToDictionary(Func&amp;lt;T,K&amp;gt; keySelector)    // puts every element in a dictionary
                                                       // using keys generated by keySelector
Dictionary&amp;lt;K,T&amp;gt; ToDictionary(Func&amp;lt;T,K&amp;gt; keySelector, IEqualityComparer&amp;lt;K&amp;gt;)
Dictionary&amp;lt;K,R&amp;gt; ToDictionary(Func&amp;lt;T,K&amp;gt; keySelector, Func&amp;lt;T,R&amp;gt; elemSelector)
                               // transforms each T to an R and puts the Rs in the dictionary
Dictionary&amp;lt;K,R&amp;gt; ToDictionary(Func&amp;lt;T,K&amp;gt; keySelector, Func&amp;lt;T,R&amp;gt; elemSelector, IEqualityComparer&amp;lt;K&amp;gt;)
Lookup&amp;lt;K,T&amp;gt; ToLookup(Func&amp;lt;T,K&amp;gt; keySelector)           // a Lookup is like a Dictionary except
                                                      // each key points to a list of values.
                                                      // In Perl terms it's a hash of arrays.
Lookup&amp;lt;K,T&amp;gt; ToLookup(Func&amp;lt;T,K&amp;gt; keySelector, IEqualityComparer&amp;lt;K&amp;gt;)
Lookup&amp;lt;K,R&amp;gt; ToLookup(Func&amp;lt;T,K&amp;gt; keySelector, Func&amp;lt;T,R&amp;gt; elemSelector)
Lookup&amp;lt;K,R&amp;gt; ToLookup(Func&amp;lt;T,K&amp;gt; keySelector, Func&amp;lt;T,R&amp;gt; elemSelector, IEqualityComparer&amp;lt;K&amp;gt;)

T Aggregate(Func&amp;lt;T,T,T&amp;gt; adder)        // like python's reduce

T ElementAt(int index)
T ElementAtOrDefault(int index)       // returns this[i] or default(T) if i &amp;gt;= this.Count

T First()
T First(Func&amp;lt;T,Boolean&amp;gt;)              // the first element that satisfies the predicate
T FirstOrDefault()
T FirstOrDefault(Func&amp;lt;T,Boolean&amp;gt;)
T Last()
T Last(Func&amp;lt;T,Boolean&amp;gt;)               // the last element that satisfies the predicate
T LastOrDefault()
T LastOrDefault(Func&amp;lt;T,Boolean&amp;gt;)

T Single()                        // returns the only element of the sequence,
                                  // or throws an exception
T Single(Func&amp;lt;T,Boolean&amp;gt; f)       // returns the only element for which f returns true.
                                  // Exception if there is not one and only one.
T SingleOrDefault()               // default(T) if empty. Still exception if more than one T.
T SingleOrDefault(Func&amp;lt;T,Boolean&amp;gt; f)

bool Contains(T)
bool Contains(T, IEqualityComparer&amp;lt;T&amp;gt;)
bool All(Func&amp;lt;T, bool&amp;gt; predicate)       // true if predicate is always true
bool Any(Func&amp;lt;T, bool&amp;gt; predicate)       // true if predicate is ever true
bool Any()                              // true if the sequence contains any elements
bool SequenceEqual(IEnumerable&amp;lt;T&amp;gt;)      // true if all the elements of the two sequences
                                        // are equal, using T's default equality comparer.
bool SequenceEqual(IEnumerable&amp;lt;T&amp;gt;, IEqualityComparer&amp;lt;T&amp;gt;)

int Count()
int Count(Func&amp;lt;T,Boolean&amp;gt;)    // counts how many elements satisfy the predicate.
long LongCount()
long LongCount(Func&amp;lt;T,Boolean&amp;gt;)

int Average()
int Average(Func&amp;lt;T,int&amp;gt; transform)    // calls transform to alter each element before
                                      // including it in the average.
                                      // You could use this to get a weighted average, e.g.
int Max()
int Max(Func&amp;lt;T,int&amp;gt; transform)        // uses transform to turn each T into an int
int Min()
int Min(Func&amp;lt;T,int&amp;gt; transform)
int Sum()
int Sum(Func&amp;lt;T,int&amp;gt; transform)
// ... lots of overloads ...

IEnumerable&amp;lt;T&amp;gt; DefaultIfEmpty()          // returns [default(T)] if empty
IEnumerable&amp;lt;T&amp;gt; DefaultIfEmpty(T elem)    // returns [elem] if empty.

IEnumerable&amp;lt;T&amp;gt; AsEnumerable()    // forces the compiler to call IEnumerable&amp;lt;T&amp;gt; methods
IEnumerable&amp;lt;R&amp;gt; Cast&amp;lt;R&amp;gt;()         // casts each element to an R
IEnumerable&amp;lt;R&amp;gt; OfType&amp;lt;R&amp;gt;()       // filters out any elements not of type R

IEnumerable&amp;lt;T&amp;gt; Intersect(IEnumerable&amp;lt;T&amp;gt; compare)    // the standard set operation
IEnumerable&amp;lt;T&amp;gt; Intersect(IEnumerable&amp;lt;T&amp;gt; compare, IEqualityComparer&amp;lt;T&amp;gt;)
IEnumerable&amp;lt;T&amp;gt; Union(IEnumerable&amp;lt;T&amp;gt; compare)        // the standard set operation
IEnumerable&amp;lt;T&amp;gt; Union(IEnumerable&amp;lt;T&amp;gt; compare, IEqualityComparer&amp;lt;T&amp;gt;)
IEnumerable&amp;lt;T&amp;gt; Except(IEnumerable&amp;lt;T&amp;gt; compare)       // returns this - compare
IEnumerable&amp;lt;T&amp;gt; Except(IEnumerable&amp;lt;T&amp;gt; compare, IEqualiterComperer&amp;lt;T&amp;gt;)

IEnumerable&amp;lt;T&amp;gt; Distinct()                      // like SQL distinct keyword
IEnumerable&amp;lt;T&amp;gt; Distinct(IEqualityComperer&amp;lt;T&amp;gt;)
IEnumerable&amp;lt;T&amp;gt; Concat(IEnumerable&amp;lt;T&amp;gt;)          // like Union, but with list semantics
                                               // instead of set
IEnumerable&amp;lt;T&amp;gt; Range(int start, int count)

IEnumerable&amp;lt;T&amp;gt; Skip(int n)                       // skips n elements; returns the rest
IEnumerable&amp;lt;T&amp;gt; SkipWhile(Func&amp;lt;T,Boolean&amp;gt; f)      // skips while f is true; returns the rest
IEnumerable&amp;lt;T&amp;gt; SkipWhile(Func&amp;lt;T,int,Boolean&amp;gt; f)  // f also gets the 0-based index
IEnumerable&amp;lt;T&amp;gt; Take(int n)                       // returns Range(0,n)
IEnumerable&amp;lt;T&amp;gt; TakeWhile(Func&amp;lt;T,Boolean&amp;gt; f)      // takes while f is true; skips the rest
IEnumerable&amp;lt;T&amp;gt; TakeWhile(Func&amp;lt;T,int,Boolean&amp;gt; f)

IEnumerable&amp;lt;T&amp;gt; While(Func&amp;lt;T,Boolean&amp;gt; f)     // gets the elements where f is true.
IEnumerable&amp;lt;T&amp;gt; While(Func&amp;lt;T,int,Boolean&amp;gt; f) // f also knows the 0-based index.

IEnumerable&amp;lt;IGrouping&amp;lt;K,T&amp;gt;&amp;gt; GroupBy(Func&amp;lt;T,K&amp;gt; f)    // f generates a key for each element
IEnumerable&amp;lt;IGrouping&amp;lt;K,R&amp;gt;&amp;gt; GroupBy(Func&amp;lt;T,K&amp;gt; f, Func&amp;lt;K, IEnumerable&amp;lt;T&amp;gt;, R&amp;gt; resultSelector)
                       // resultSelector gets an enumeration of values with a given key,
                       // and it returns a single value of type R, e.g. representing
                       // their min value. Note that you could use anonymous classes
                       // to stick several values into R, e.g. a min, max, and average.
                       // There is a nice example here:
                       // [http://msdn.microsoft.com/en-us/library/bb549393.aspx](http://msdn.microsoft.com/en-us/library/bb549393.aspx).
... lots more overloads ...

IOrderedEnumerable&amp;lt;T&amp;gt; OrderBy(Func&amp;lt;T,K&amp;gt; keySelector)    // orders the elements based on keys
                                                        // generated by keySelector
IOrderedEnumerable&amp;lt;T&amp;gt; OrderBy(Func&amp;lt;T,K&amp;gt; keySelector, IComparer&amp;lt;K&amp;gt; comp)
                                // orders the elements based on keys generated by keySelector
                                // and compared by comp
IOrderedEnumerable&amp;lt;T&amp;gt; OrderByDescending(Func&amp;lt;T,K&amp;gt; keySelector)
IOrderedEnumerable&amp;lt;T&amp;gt; OrderByDescending(Func&amp;lt;T,K&amp;gt; keySelector, IComparer&amp;lt;K&amp;gt; comp)
IEnumerable&amp;lt;T&amp;gt; Reverse()
IOrderedEnumerable&amp;lt;T&amp;gt; ThenBy(Func&amp;lt;T,K&amp;gt; keySelector)     // sub-sorts elements deemed equal
                                                        // by a previous sort
IOrderedEnumerable&amp;lt;T&amp;gt; ThenBy(Func&amp;lt;T,K&amp;gt; keySelector, IComparer&amp;lt;K&amp;gt; comp)
IOrderedEnumerable&amp;lt;T&amp;gt; ThenByDescending(Func&amp;lt;T,K&amp;gt; keySelector)
IOrderedEnumerable&amp;lt;T&amp;gt; ThenByDescending(Func&amp;lt;T,K&amp;gt; keySelector, IComparer&amp;lt;K&amp;gt; comp)

IEnumerable&amp;lt;T&amp;gt; Join(IEnumerable&amp;lt;I&amp;gt; inner, Func&amp;lt;O,K&amp;gt; outerKeySelector,
        Func&amp;lt;I,K&amp;gt; innerKeySelector, Func&amp;lt;O,I,R&amp;gt; resultSelector)
                // joins two sequences as an inner equijoin.
                // There is no method for outer joins,
                // but GroupJoin can get used to get that effect.
IEnumerable&amp;lt;O,I,K,R&amp;gt; GroupJoin(IEnumerable&amp;lt;I&amp;gt; inner, Func&amp;lt;O,K&amp;gt; outerKeySelector,
        Func&amp;lt;I,K&amp;gt; innerKeySelector, Func&amp;lt;O, IEnumerable&amp;lt;I&amp;gt;, R&amp;gt; resultSelector)
                // joins the two sequences (see Join) and groups the results (see GroupBy).
                // Unlike with Join, this function can be used to do a left outer join,
                // because even when there is no value in inner matching a value in outer,
                // the resultSelector gets called for each outer value,
                // just with an empty IEnuemrable&amp;lt;I&amp;gt;.

IEnumerable&amp;lt;R&amp;gt; Select(Func&amp;lt;T,R&amp;gt; f)                  // uses f to transform each T to an R
IEnumerable&amp;lt;R&amp;gt; Select(Func&amp;lt;T,int,R&amp;gt; f)              // f also knows the 0-based index of each T
IEnumerable&amp;lt;R&amp;gt; SelectMany(Func&amp;lt;T,IEnumerable&amp;lt;R&amp;gt; f)  // f can return many Rs. All the Rs
                                                    // are flattened into one sequence.
IEnumerable&amp;lt;R&amp;gt; SelectMany(Func&amp;lt;T,int,IEnumerable&amp;lt;R&amp;gt; f)
IEnumerable&amp;lt;R&amp;gt; SelectMany(Func&amp;lt;T,IEnumerable&amp;lt;U&amp;gt; f, Func&amp;lt;T,U,R&amp;gt; g)
                // f generates an intermediate value of type U; g uses both a T and U
                // to get an R. This is really only useful if U doesn't have access to T.
                // See the example code here:
                // [http://msdn.microsoft.com/en-us/library/bb534631.aspx](http://msdn.microsoft.com/en-us/library/bb534631.aspx).
IEnumerable&amp;lt;R&amp;gt; SelectMany(Func&amp;lt;T,int,IEnumerable&amp;lt;U&amp;gt; f, Func&amp;lt;T,U,R&amp;gt; g)&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
</content>
  </entry>
  <entry>
    <id>tag:illuminatedcomputing.com,2010-03-15:/posts/2010/03/equals-and-compareto-in-subclasses/</id>
    <title type="html">Equals and compareTo in Subclasses</title>
    <published>2010-03-15T00:00:00Z</published>
    <updated>2010-03-15T00:00:00Z</updated>
    <link rel="alternate" href="https://illuminatedcomputing.com/posts/2010/03/equals-and-compareto-in-subclasses/" type="text/html"/>
    <content type="html">
&lt;p&gt;The other day I read &lt;a href="http://www.artima.com/lejava/articles/equality.html"&gt;this interesting paper&lt;/a&gt; on contructing a correct &lt;code&gt;equals&lt;/code&gt; method when subclassing. It is about Java, but it applies equally well to C#. They cite Josh Bloch’s book &lt;a href="http://www.amazon.com/Effective-Java-2nd-Joshua-Bloch/dp/0321356683/"&gt;Effective Java&lt;/a&gt;, who writes:&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;There is no way to extend an instantiable class and add a value component while preserving the equals contract, unless you are willing to forgo the benefits of object-oriented abstraction. I read this book a while back—maybe six or seven years ago now. At the time I thought it was invaluable. It seemed like the Java version of &lt;a href="http://www.amazon.com/Expert-Programming-Peter-van-Linden/dp/0131774298/"&gt;Expert C Programming: Deep C Secrets&lt;/a&gt; (the fish book). But when I think back on it now, all I can remember is the author’s ongoing struggle to overcome Java’s limitations and contradictions. It seemed he was constantly recommending more and more verbose code to get around problems in the underlying language. I guess that’s not Bloch’s fault, but Java just seems to be like that. It’s the reason my resume has a crowded half-page of Java TLAs.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Anyway, contrary to Bloch’s commonly-accepted denial, the authors of the paper present a way to write an equals method that preserves the contract of equals even when extending from another non-abstract class and adding more state. Their solution isn’t even that verbose or twisted. It’s worth a read. Basically they recommend this (some parts changed for brevity):&lt;/p&gt;

&lt;div class="CodeRay"&gt;&lt;div class="code"&gt;&lt;pre&gt;&lt;code class="language-csharp"&gt;public class Point {
    public int x;
    public int y;

    public boolean equals(Object other) {
        boolean result = false;
        if (other instanceof Point) {
            Point that = (Point)other;
            result = that.canEqual(this) &amp;amp;&amp;amp; this.x == that.x &amp;amp;&amp;amp; this.y == that.y;
        }
        return result;
    }

    public boolean canEqual(Object other) {
        return (other instanceof Point);
    }

    public int hashCode() {
        return 41 * (41 + x) + y;
    }
}

public class ColoredPoint extends Point {
    public Color color;

    public boolean equals(Object other) {
        boolean result = false;
        if (other instanceof ColoredPoint) {
            ColoredPoint that = (ColoredPoint)other;
            result = that.canEqual(this) &amp;amp;&amp;amp; color.equals(that.color) &amp;amp;&amp;amp; super.equals(that);
        }
        return result;
    }

    public boolean canEqual(Object other) {
        return (other instanceof ColoredPoint);
    }

    public int hashCode() {
        return 41 * super.hashCode() + color.hashCode();
    }
}&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;The trick here is that &lt;code&gt;canEquals&lt;/code&gt; method. It is not really a public method; it is only called from within the &lt;code&gt;equals&lt;/code&gt; method. But note that an object doesn’t call it’s own &lt;code&gt;canEquals&lt;/code&gt; method; it calls it &lt;em&gt;on the other object&lt;/em&gt;. This lets the two objects agree that they are really equal, and it solves the problem of non-symmetric implementations of &lt;code&gt;equals&lt;/code&gt; (where &lt;code&gt;a.equals(b) != b.equals(a)&lt;/code&gt;). This is a common problem, because a Point might think it equals a ColoredPoint, whereas the ColoredPoint knows it doesn’t equal the Point.&lt;/p&gt;

&lt;p&gt;The naive way of ensuring symmetry would be to replace &lt;code&gt;instanceof&lt;/code&gt; with a comparison of the object’s actual class. But this is too crude, because it means you can’t use anonymous classes. For instance, a Point should still equal an anonymous class instance like this one:&lt;/p&gt;

&lt;div class="CodeRay"&gt;&lt;div class="code"&gt;&lt;pre&gt;&lt;code class="language-csharp"&gt;Point pAnon = new Point() {
    public void overrideSomeMethod() {
        // ...
    }
}&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;With &lt;code&gt;canEquals&lt;/code&gt;, the anonymous class simple inherits &lt;code&gt;canEquals&lt;/code&gt; from Point, and the two objects will still agree on their equality. I think this is a really nice solution to a thorny problem.&lt;/p&gt;

&lt;p&gt;The forum discussion about the paper (which is almost as good as the paper itself) argues that Java ought to support an &lt;code&gt;Equalator&lt;/code&gt; interface as a parallel to &lt;code&gt;Comparator&amp;lt;T&amp;gt;&lt;/code&gt;. The idea is that just as you can override the “natural ordering” of a class, you should be able to override its “natural equivalence.” This would let you instantiate a &lt;code&gt;Set&lt;/code&gt;, &lt;code&gt;HashMap&lt;/code&gt;, etc. with an &lt;code&gt;Equalator&lt;/code&gt; to get a different notion of equals than usual. Just as objects may sort differently in different contexts, so they may “be equal” differently in different contexts, depending on what you care about. Who hasn’t run into the need for a &lt;code&gt;Set&lt;/code&gt; based on reference identity, for example? Apache Collections provides just such a class.&lt;/p&gt;

&lt;p&gt;The need for an &lt;code&gt;Equalator&lt;/code&gt; seems most pressing in classes like &lt;code&gt;TreeSet&lt;/code&gt; that use &lt;code&gt;compareTo&lt;/code&gt; rather than &lt;code&gt;equals&lt;/code&gt; to test for set duplicates. If you use a &lt;code&gt;TreeSet&lt;/code&gt; with a &lt;code&gt;Comparator&lt;/code&gt; that is not consistent with equals, that the &lt;code&gt;TreeSet&lt;/code&gt; will appear to violate the set contract, because you could have &lt;code&gt;a.equals(b)&lt;/code&gt; but &lt;code&gt;s.contains(a) != s.contains(b)&lt;/code&gt;. I went to bed thinking it’s a shame Sun hasn’t added this &lt;code&gt;Equalator&lt;/code&gt; concept.&lt;/p&gt;

&lt;p&gt;But as I was thinking about it over the night, I started to believe Sun is right to leave it out, at least in so far as it pertains to classes like &lt;code&gt;TreeSet&lt;/code&gt; that use &lt;code&gt;compareTo&lt;/code&gt; instead of &lt;code&gt;equals&lt;/code&gt;. Basically, the &lt;code&gt;TreeSet&lt;/code&gt;‘s &lt;code&gt;Comparator&lt;/code&gt; is already operating as an &lt;code&gt;Equalator&lt;/code&gt; here. Why do you need an &lt;code&gt;Equalator&lt;/code&gt;, too? What problem would it solve that isn’t already solved by the &lt;code&gt;Comparator&lt;/code&gt;? If you passed an &lt;code&gt;Equalator&lt;/code&gt; to a &lt;code&gt;TreeSet&lt;/code&gt;, it wouldn’t change this code problem: &lt;code&gt;a.equals(b) &amp;amp;&amp;amp; (s.contains(a) != s.contains(b))&lt;/code&gt;. The whole point of an &lt;code&gt;Equalator&lt;/code&gt; is to impose a different notion of equality &lt;em&gt;on a limited context&lt;/em&gt;, and with &lt;code&gt;TreeSet&lt;/code&gt; a &lt;code&gt;Comparator&lt;/code&gt; is sufficient for that.&lt;/p&gt;

&lt;p&gt;Of course, that’s not to say an &lt;code&gt;Equalator&lt;/code&gt; wouldn’t be useful in a regular &lt;code&gt;Set&lt;/code&gt; or &lt;code&gt;Map&lt;/code&gt;. It turns out that C# does have the &lt;code&gt;Equalator&lt;/code&gt; idea, but it’s called &lt;code&gt;IEqualityComparer&amp;lt;T&amp;gt;&lt;/code&gt;. It doesn’t seem to be used much, but &lt;code&gt;Dictionary&amp;lt;K,V&amp;gt;&lt;/code&gt; and &lt;code&gt;HashSet&amp;lt;T&amp;gt;&lt;/code&gt; both support it.&lt;/p&gt;

&lt;p&gt;I actually came across this paper while thinking about how C#‘s &lt;code&gt;CompareTo&amp;lt;T&amp;gt;&lt;/code&gt; can work in a class heirarchy. As in Java, this method must be “consistent with &lt;code&gt;Equals&lt;/code&gt;.” That is, whenever &lt;code&gt;Equals&lt;/code&gt; returns true, &lt;code&gt;CompareTo&lt;/code&gt; must return 0, and whenever &lt;code&gt;CompareTo&lt;/code&gt; returns 0, &lt;code&gt;Equals&lt;/code&gt; must return true. Put into code, &lt;code&gt;(a.CompareTo(b) == 0) == a.Equals(b)&lt;/code&gt;. The &lt;code&gt;CompareTo&lt;/code&gt; method is tricky because it’s parameterized: its signature is &lt;code&gt;bool CompareTo(T o)&lt;/code&gt;, where &lt;code&gt;T&lt;/code&gt; comes from &lt;code&gt;IComparable&amp;lt;T&amp;gt;&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;So what happens if you have &lt;code&gt;Base : IComparable&amp;lt;Base&amp;gt;&lt;/code&gt; and &lt;code&gt;Subclass : Base, IComparable&amp;lt;Subclass&amp;gt;&lt;/code&gt;? My instinct is you’re asking for trouble, although when I think it through it seems that the compiler will choose the method based on the current static type, not the instance’s actual type, so maybe you’d be okay. If your code is interested in comparing Bases, you’ll call that method; you’ll only call &lt;code&gt;CompareTo(Subclass o)&lt;/code&gt; if you’re explicitly comparing Subclasses. So maybe everything will work out, but I’m still uneasy.&lt;/p&gt;

&lt;p&gt;I also see that C# 4.0 is supporting new keywords for co- and contra-variance in generic parameters. So we get &lt;code&gt;IEnumerable&amp;lt;out T&amp;gt;&lt;/code&gt; and &lt;code&gt;IComparable&amp;lt;in T&amp;gt;&lt;/code&gt;. This means that if you implement &lt;code&gt;IEnumerator&amp;lt;Subclass&amp;gt; GetEnumerator&lt;/code&gt;, you also fulfill the contract for &lt;code&gt;IEnumerable&amp;lt;Base&amp;gt;&lt;/code&gt;, and if you implement &lt;code&gt;CompareTo(Base o)&lt;/code&gt;, your subclass doesn’t have to implement &lt;code&gt;CompareTo(Subclass o)&lt;/code&gt; in order to fulfill the contract for &lt;code&gt;IComparable&amp;lt;Subclass&amp;gt;&lt;/code&gt;. I hope I’ve got that right!&lt;/p&gt;

&lt;p&gt;The first part—covariant return types—seems like the bigger deal here. (I only wish it were &lt;em&gt;full&lt;/em&gt; covariant return types as in C++!) But the part about &lt;code&gt;IComparable&lt;/code&gt; seems nice, too. It should save a bit of code, because it means that if you have a full-featured base class and you want to write a quick subclass on top of it, you can still use your subclass in things that require an &lt;code&gt;IComparable&amp;lt;Subclass&amp;gt;&lt;/code&gt; (like &lt;code&gt;List&amp;lt;Subclass&amp;gt;&lt;/code&gt;) without writing another &lt;code&gt;CompareTo&lt;/code&gt; implementation.&lt;/p&gt;
</content>
  </entry>
  <entry>
    <id>tag:illuminatedcomputing.com,2010-03-11:/posts/2010/03/viewing-unit-test-output-in-visual-studio/</id>
    <title type="html">Viewing Unit Test Output in Visual Studio</title>
    <published>2010-03-11T00:00:00Z</published>
    <updated>2010-03-11T00:00:00Z</updated>
    <link rel="alternate" href="https://illuminatedcomputing.com/posts/2010/03/viewing-unit-test-output-in-visual-studio/" type="text/html"/>
    <content type="html">
&lt;p&gt;I’ve been using Visual Studio 2008 to write unit tests. I had a couple failing in very strange ways, and I wanted to add some debugging statements to watch the state of the code. I usually find this more useful than running a debugger. (If that seems weak, then I’ll just say that K &amp;amp; R agrees with me!) I can print whatever state I want and I don’t have to deal with breakpoints. Furthermore, once those debugging messages are in there, I can leave them there so they help out next time.&lt;/p&gt;

&lt;p&gt;The problem was that I couldn’t figure out how to see Console output for unit tests. I kept trying to open various Output windows: Build output, Debug output, Refactor output. No Test output! Googling didn’t turn up anything. Today I was hitting the same problem, so I thought I’d try Googling one more time. I must have hit the magic search term combination, because this time all my top results were relevant.&lt;/p&gt;

&lt;p&gt;It turns out to see a test’s output, you just double-click on the test summary line, and all the output is down at the bottom of that window. You get Console.Out messages and (more importantly) {Trace,Debug}.WriteLine(). Wonderful!&lt;/p&gt;
</content>
  </entry>
  <entry>
    <id>tag:illuminatedcomputing.com,2010-02-27:/posts/2010/02/c-xmltextreader-tutorial/</id>
    <title type="html">C# XmlTextReader Tutorial</title>
    <published>2010-02-27T00:00:00Z</published>
    <updated>2010-02-27T00:00:00Z</updated>
    <link rel="alternate" href="https://illuminatedcomputing.com/posts/2010/02/c-xmltextreader-tutorial/" type="text/html"/>
    <content type="html">
&lt;p&gt;I needed to read a big XML file into an object structure. I wanted it to be fast and use a low memory footprint. I also wanted the XML to stay pretty clean to make future support easy. Because of the speed and memory requirements, DOM and XPath were out. I toyed around with XmlSerializer, but it didn’t quite give me the XML I wanted—too ugly—and I didn’t like cluttering my classes with xml serialization attributes. That doesn’t belong in the objects, does it? And then the code to structure the XML is scattered around everywhere. And finally, what if I need to serialize the objects in different ways at different times?&lt;/p&gt;

&lt;p&gt;So I thought I’d try my hand at XmlTextReader, which is a bit like SAX but more “push” than “pull.” It’s not based on callbacks, and you don’t have to manage state so attentively. Coming from the Java world, I’m used to SAX. I actually like it. The state machine thing isn’t so hard, really. So I was pretty excited about XmlTextReader. It looked like it would have the advantages of SAX but be easier to use.&lt;/p&gt;

&lt;p&gt;Having now written some code with XmlTextReader, I’m still pretty happy with it, but I’m a bit disappointed that Microsoft junked up the API so much. It seems gappy and needlessly complicated. But having learned it, I thought I’d set it all down in writing.&lt;/p&gt;

&lt;p&gt;One approach, which is fairly SAX-like, is to put everything into a read loop and switch on element names. That might look like this:&lt;/p&gt;

&lt;div class="CodeRay"&gt;&lt;div class="code"&gt;&lt;pre&gt;&lt;code class="language-csharp"&gt;XmlTextReader r = new XmlTextReader(stream);
r.WhiteSpaceHandling = WhiteSpaceHandling.None;
while (r.Read()) {
  if (r.NodeType.Equals(XmlNodeType.Element)) {
    switch (r.LocalName) {
      case "this":
        // processing ...
        break;
      case "that":
        // processing ...
        break;
      // more cases ...
    }
  }
}&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;If you wanted, you could stop there. The Read() method gives you one node at a time, and you handle each element. You could add code to handle endElements also, or comments, or whatever, just as in SAX. But there are lots of other methods to make things easier.&lt;/p&gt;

&lt;p&gt;If you’ve never done this sort of thing before, you should know that an XML document consists of nodes. A node can be a start element, an end element, a run of text, a comment, a processing instruction, even whitespace. By setting WhitespaceHandling to None above, we told the XmlTextReader to skip whitespace, so Read() doesn’t report it. Attributes are nodes too, but the Read loop doesn’t emit them, either. Instead you use special methods to get at attributes when you’re positioned on their containing element. As you can see, some nodes have children (e.g. some elements), whereas other nodes are leaves (text, attributes, other elements).&lt;/p&gt;

&lt;p&gt;One tricky thing is to keep track of your current position in the document. In describing the various methods below, I’ll try to pay attention to how they affect the document position. The Read() element advances one node.&lt;/p&gt;

&lt;p&gt;First let’s talk about some methods that look useful but you should probably avoid. One is ReadElementString(). This advances one element and returns the contents of the next element as a string. A variant is ReadElementString(elemName), which verifies that the current element matches the given name. I didn’t find these methods too useful. The first gives you no checking to see if you’re actually reading the right thing. The second checks the wrong thing. I don’t want to test the current element and then read the contents of the next one. The test needs to be the name of the next element. Both of these methods read the element blindly; the latter just looks backwards a bit.&lt;/p&gt;

&lt;p&gt;Another method to avoid is ReadString(). This returns a string when positioned on either an element or a text node. That’s handy, but it doesn’t skip comments and processing instructions very well. For that we’ll need a different method.&lt;/p&gt;

&lt;p&gt;One method that looks great is MoveToElement(elemName). But if you think this will scan through the document until it finds your desired element, you’re wrong. Instead, this is used in attribute processing to move up from the attributes back to their owning element. Alas!&lt;/p&gt;

&lt;p&gt;One method that really is handy is MoveToContent. This skips over comments, whitespace, processing instructions, and documentType nodes. In all your processing, you should be aware that users may throw comments into weird places. Robust XML parsing doesn’t get tripped up by comments. So this call is quite useful.&lt;/p&gt;

&lt;p&gt;To get the contents of an element, ignoring any comments, you want the ReadContentAsXXX() methods and the ReadElementContentAsXXX() methods. These methods skip comments and processing instructions and automatically convert entities. This is just the sort of friendly assistance you want from your XML parser. As for the XXX, you have a lot of options. It could be String, Int, DateTime, even Object.&lt;/p&gt;

&lt;p&gt;The difference between ReadConentAs and ReadElementContentAs is this: the first must be positioned on a text node, whereas the latter can be positioned on either a text node or the text’s containing element. If you call ReadContentAs on an element, you get an exception. In practice, I think ReadElementContentAs is the more useful family of methods. Also, when it returns, the reader is positioned at whatever follows the endElement node of what you just read. If you’re ignoring whitespace, this could be the next element. (Or it could be a comment, etc.)&lt;/p&gt;

&lt;p&gt;Then there are a few methods for moving around in the document. I think this is where the API really falls short, but here’s what we’ve got: ReadToFollowing, ReadToNextSibling, and ReadToDescendant. All these methods take an element name and return true if it is found, leaving you positioned on the element node (and ready to call ReadElementContentAs). If they can’t find what you want, they return false, and then your new position in the document is however far they’ve searched. You’ll be at EOF for ReadToFollowing, or the end tag of the current/parent element for the other two. This is a bit of a disappointment. If you’re looking for a required element, you could just throw an exception, but what about finding optional elements? It’s no big deal the element wasn’t there, but you’re way off course.&lt;/p&gt;

&lt;p&gt;One other useful method is Skip(). This skips the children of the current node.&lt;/p&gt;

&lt;p&gt;Here is some code making use of these elements to parse a fairly simply document. The document describes a family, with elements for headOfHousehold, spouse, and children. Each person has a name, birthdate, and sex. Let’s treat the last two of these as optional. The spouse node can also have an optional marriageDate element. We could indicate the XML structure like this, where wildcards have their usual meaning (? = 0 or 1, * = 0 or more, + = 1 or more):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;family
  headOfHousehold
    name
      birthdate?
      sex?
  spouse?
    name
    birthdate?
    sex?
    marriageDate?
  children?
    child+
      name
      birthdate?
      sex?&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here is some code that processes such a file by building up an object structure, then prints the results:&lt;/p&gt;

&lt;div class="CodeRay"&gt;&lt;div class="code"&gt;&lt;pre&gt;&lt;code class="language-csharp"&gt;using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;

namespace XmlTextReaderTest {

    public enum Sex { MALE, FEMALE }

    public class Person {
        public string Name { get; set; }
        public DateTime Birthdate { get; set; }
        public Sex Sex { get; set; }
        public DateTime? MarriageDate { get; set; }

        public override string ToString() {
            return String.Format("{0}: {1}, {2:yyyy-MM-dd}, {3:yyyy-MM-dd}", Name, Sex, Birthdate, MarriageDate);
        }
    }

    public class Family {
        public Person Head { get; set; }
        public Person Spouse { get; set; }
        public List&amp;lt;Person&amp;gt; Children { get; private set; }

        public Family() {
            Children = new List&amp;lt;Person&amp;gt;();
        }

        public override String ToString() {
            String ret = "Head:\n\t" + Head + "\nSpouse:\n\t" + Spouse + "\n";
            foreach (Person p in Children) {
                ret += "Child:\n\t" + p + "\n";
            }
            return ret;
        }
    }

    public class Program {
        static void Main(string[] args) {
            string xmlDoc = @"&amp;lt;?xml version='1.0' encoding='utf-8'?&amp;gt;
&amp;lt;family&amp;gt;
    &amp;lt;headOfHousehold&amp;gt;
      &amp;lt;name id='asdf'&amp;gt;Paul Jungwirth&amp;lt;/name&amp;gt;
      &amp;lt;!-- not my real birthday of course: --&amp;gt;
      &amp;lt;birthdate&amp;gt;1975-02-08&amp;lt;/birthdate&amp;gt;
      &amp;lt;sex&amp;gt;male&amp;lt;/sex&amp;gt;
    &amp;lt;/headOfHousehold&amp;gt;
    &amp;lt;spouse&amp;gt;
      &amp;lt;name&amp;gt;Arielle Jungwirth&amp;lt;/name&amp;gt;
      &amp;lt;birthdate&amp;gt;1979-11-11&amp;lt;/birthdate&amp;gt;
      &amp;lt;sex&amp;gt;female&amp;lt;/sex&amp;gt;
      &amp;lt;marriageDate&amp;gt;2006-09-09&amp;lt;/marriageDate&amp;gt;
    &amp;lt;/spouse&amp;gt;
    &amp;lt;children&amp;gt;
      &amp;lt;child&amp;gt;
        &amp;lt;name&amp;gt;James Jungwirth&amp;lt;/name&amp;gt;
        &amp;lt;birthdate&amp;gt;2007-12-31&amp;lt;/birthdate&amp;gt;
        &amp;lt;sex&amp;gt;male&amp;lt;/sex&amp;gt;
      &amp;lt;/child&amp;gt;
      &amp;lt;child&amp;gt;
        &amp;lt;name&amp;gt;Miriam Jungwirth&amp;lt;/name&amp;gt;
        &amp;lt;birthdate&amp;gt;2010-01-20&amp;lt;/birthdate&amp;gt;
        &amp;lt;sex&amp;gt;female&amp;lt;/sex&amp;gt;
      &amp;lt;/child&amp;gt;
    &amp;lt;/children&amp;gt;
&amp;lt;/family&amp;gt;";
            Family f = ParseFamily(new MemoryStream(Encoding.Default.GetBytes(xmlDoc)));
            Console.Write(f);
            Console.ReadLine();
        }

        public static Family ParseFamily(Stream stream) {
            Family f = new Family();
            XmlTextReader r = new XmlTextReader(stream);
            r.WhitespaceHandling = WhitespaceHandling.None;
            r.MoveToContent();

            while (r.Read()) {
                // Console.WriteLine(r.NodeType + ": " + r.LocalName + "\n");
                if (r.NodeType.Equals(XmlNodeType.Element)) {
                    switch (r.LocalName) {
                        case "headOfHousehold":
                            f.Head = ParsePerson(r);
                            break;
                        case "spouse":
                            f.Spouse = ParsePerson(r);
                            f.Head.MarriageDate = f.Spouse.MarriageDate;
                            break;
                        case "child":
                            f.Children.Add(ParsePerson(r));
                            break;
                        default:
                            // ignore other nodes
                            break;
                    }
                }
            }

            return f;
        }

        public static Person ParsePerson(XmlTextReader r) {
            Person p = new Person();

            // Right now we're pointing to the person's containing element, e.g. headOfHousehold.
            // Read past that, then read until we get to a new start element.
            r.Read();

            r.MoveToContent();
            if (r.LocalName.Equals("name")) p.Name = r.ReadElementContentAsString();
            else throw new InvalidDataException("no name for person");

            r.MoveToContent();
            if (r.LocalName.Equals("birthdate")) p.Birthdate = r.ReadElementContentAsDateTime();

            r.MoveToContent();
            if (r.LocalName.Equals("sex")) p.Sex = (Sex)Enum.Parse(typeof(Sex), r.ReadElementContentAsString(), true);

            r.MoveToContent();
            if (r.LocalName.Equals("marriageDate")) p.MarriageDate = r.ReadElementContentAsDateTime();

            return p;
        }
    }
}&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;p&gt;This code demonstrates on a small scale the pattern I use to parse XML documents and keep the code manageable. I read through the whole document using our Read/switch loop, and I call out to helper functions to build objects representing significant chunks. These methods may call other helper functions or (as here) just navigate through the XML to pick out primitives. Each chunk of code is self-contained, and you’re never looking at more than a page or so.&lt;/p&gt;

&lt;p&gt;You can see that in building each Person, I use MoveToContent and then test the name of the next element. Calling ReadElementContentAs takes me past the endElement, so afterwards I’m ready to read some more. If I’m already on an element, MoveToContent won’t advance at all, so it’s safe to call twice in the case when an optional element is missing.&lt;/p&gt;

&lt;p&gt;You could also implement ParsePerson as a second Read/switch loop. That would mean the child elements can come in any order, but you’d have to verify at the end that you got data for all the required ones. You also may not know when to exit, if the name of your endElement can vary as in this example (e.g. “spouse” vs. “child”).&lt;/p&gt;
</content>
  </entry>
  <entry>
    <id>tag:illuminatedcomputing.com,2010-02-13:/posts/2010/02/sorting-out-the-confusion-32-vs-64-bit-clr-vs-native-cs-vs-cpp/</id>
    <title type="html">Sorting Out the Confusion: 32- vs. 64-Bit, CLR vs. Native, C# vs. C++</title>
    <published>2010-02-13T00:00:00Z</published>
    <updated>2010-02-13T00:00:00Z</updated>
    <link rel="alternate" href="https://illuminatedcomputing.com/posts/2010/02/sorting-out-the-confusion-32-vs-64-bit-clr-vs-native-cs-vs-cpp/" type="text/html"/>
    <content type="html">
&lt;p&gt;I’ve been trying to learn how things work on Windows based on whether you write code in C# or C++, target a 32- or 64-bit platform, and produce files with either native code or one of the CLR options. One of my focuses is the interaction between exes and dlls. I think I’ve got things mostly straightened out, so this is what I’ve learned.&lt;/p&gt;

&lt;p&gt;First, the basics: a 32-bit platform can run 32-bit apps, but not 64-bit apps. A 64-bit platform can run either, but 32-bit apps run in an emulation environment called WOW64 (Windows on Windows 64). When Windows starts your app, it decides whether WOW64 is necessary. You can &lt;a href="http://msdn.microsoft.com/en-us/library/ms684139%28VS.85%29.aspx"&gt;tell whether your app is running in WOW64&lt;/a&gt; using this C++ code:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#include "stdafx.h"
#include &amp;lt;windows.h&amp;gt;

typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);

LPFN_ISWOW64PROCESS fnIsWow64Process;

BOOL isWow64() {
    BOOL ret = FALSE;
    fnIsWow64Process = (LPFN_ISWOW64PROCESS)GetProcAddress(
        GetModuleHandle(TEXT("kernel32")), "IsWow64Process");

    if (NULL != fnIsWow64Process) {
        if (!fnIsWow64Process(GetCurrentProcess(), &amp;amp;ret)) {
            printf("Got some error\n");
        }
    }
    return ret;
}

int _tmain(int argc, _TCHAR* argv[]) {
    if (isWow64()) {
        printf("Running under WOW64.\n");
    } else {
        printf("NOT running under WOW64.\n");
    }
    scanf("press return");
    return 0;
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It’s easy enough to call &lt;code&gt;isWow64&lt;/code&gt; from C#, like so:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;[DllImport]("IsWow64Dll.dll")]
static extern bool isWow64();

static void Main(String[] args) {
    Console.WriteLine(isWow64().ToString());
    Console.ReadLine();
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Visual Studio lets you build files for either 32- or 64-bit platforms. I’ve already written how to &lt;a href="/posts/2010/01/enabling-64-bit-support-in-visual-studio-2008/"&gt;build for 32 or 64 bits in C++&lt;/a&gt;. C# actually provides &lt;em&gt;three&lt;/em&gt; options: 32-bits, 64-bits, or “Any CPU.” We can use a tool called corflags to see what results we get depending on which option we choose. Corflags comes with Visual Studio and can be run by choosing the special DOS prompt command under Visual Studio in the Start menu. This is a little different from the regular DOS prompt: it has a specially-tailored environment for running Visual Studio’s command-line utilities. From there, you can ask corflags to report information about any exe or dll, like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;C:\&amp;gt; corflags myapp.exe
Microsoft (R) .NET Framework CorFlags Conversion Tool.  Version  3.5.21022.8
Copyright (c) Microsoft Corporation.  All rights reserved.

Version   : v2.0.50727
CLR Header: 2.5
PE        : PE32
CorFlags  : 3
ILONLY    : 1
32BIT     : 1
Signed    : 0&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We’re mostly interested in three values: PE, 32BIT, and ILONLY. There is also a line labelled “Signed,” which I’m not interested in right now. Finally, the “CorFlags” line appears to be a combination of the four other values.&lt;/p&gt;

&lt;p&gt;PE specifies whether or not the file can run on 32-bit platforms. It is either PE32 or PE32+. A PE32+ file cannot run on a 32-bit machine.&lt;/p&gt;

&lt;p&gt;Next there is the 32BIT flag. This is a little different from PE. If PE indicates whether your app &lt;em&gt;can&lt;/em&gt; run as 32 bits, then 32BIT indicates whether it &lt;em&gt;must&lt;/em&gt; run as 32 bits. If this flag is 0, your app can run on a 64-bit machine without WOW64. But if the flag is 1, then your app has to run under WOW64. Here is a table showing how the bits are set depending on your compiler’s /platform setting:&lt;/p&gt;
&lt;table&gt;
  &lt;tr&gt;
&lt;th&gt;Compiler Option&lt;/th&gt;
&lt;th&gt;PE&lt;/th&gt;
&lt;th&gt;32BIT&lt;/th&gt;
&lt;/tr&gt;
  &lt;tr&gt;
&lt;td&gt;x86&lt;/td&gt;
&lt;td&gt;PE32&lt;/td&gt;
&lt;td&gt;1&lt;/td&gt;
&lt;/tr&gt;
  &lt;tr&gt;
&lt;td&gt;Any CPU&lt;/td&gt;
&lt;td&gt;PE32&lt;/td&gt;
&lt;td&gt;0&lt;/td&gt;
&lt;/tr&gt;
  &lt;tr&gt;
&lt;td&gt;x64&lt;/td&gt;
&lt;td&gt;PE32+&lt;/td&gt;
&lt;td&gt;0&lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;
&lt;p&gt;From this table, you can see that the corflags example above is inspecting a C# app built for the x86 platform. Note that you could never have a file that is PE32+ with the 32BIT flag set, because then one flag would require 32 bits and the other 64.&lt;/p&gt;

&lt;p&gt;To put all this together, a 32-bit machine can run anything with a PE set to PE32, but nothing with a PE of PE32+. A 64-bit machine can run your file in 64-bit mode as long as 32BIT is 0, but if 32BIT is 1 then it must use WOW64.&lt;/p&gt;

&lt;p&gt;The ILONLY flag indicates that your file contains only MSIL opcodes (recently renamed to CIL), with no native assembly instructions. A C# app will always have this flag set (unless you use something like &lt;a href="http://msdn.microsoft.com/en-us/library/6t9t5wcf%28VS.80%29.aspx"&gt;ngen&lt;/a&gt; to compile down to machine language—an approach with &lt;a href="https://web.archive.org/web/20120306020205/http://www.codeguru.com:80/Csharp/.NET/net_general/toolsand3rdparty/article.php/c4651"&gt;some distribution problems&lt;/a&gt;), but a C++ app’s setting depends on your compiler options (described below).&lt;/p&gt;

&lt;p&gt;When it comes to loading dlls, these flags control whether your app loads the dll successfully or gets a BadImageFormatException. Basically, a 32-bit app can only load 32-bit dlls, and a 64-bit app can only load 64-bit dlls. But what about apps compiled as “Any CPU”? In that case, you can only load dlls matching whatever bitness you’re currently running as. Of course, if you’re running on a 32-bit machine, there is no complication, because everything is 32-bit already.&lt;/p&gt;

&lt;p&gt;But on a 64-bit machine, you may have problems. Windows will not use WOW64 for your app, because it claims to support 64-bit operation. But if your app has a dependency on a 32-bit dll, then you’ll get a BadImageFormatException, because the 32-bit dll only works in WOW64. The choice to use WOW64 happens only when starting your app. You can’t run an app natively and load just the dlls in WOW64. So you get the exception.&lt;/p&gt;

&lt;p&gt;The solution is to tell Windows that your app must start in WOW64 from the beginning. You should probably do this by building your app for x86, not Any CPU, but if that is somehow a problem (e.g. you don’t have the code), then you can use corflags to set the 32BIT flag. You just type something like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;corflags /32BIT+ myapp.exe&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;For C++ applications, you can do something similar with &lt;a href="http://msdn.microsoft.com/en-us/library/31zwwc39%28VS.80%29.aspx"&gt;the linker’s /clrimagetype flag&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Another choice, at least when writing in C++, is how to support the CLR. You can choose among four options: native (the default), /clr, /clr:pure, and /clr:safe. The first one is simple enough: you get a file with machine language instructions. The other three give you a file that is partially or entirely composed of MSIL. Using /clr will produce a CLR header and mostly MSIL code, but with some native code mixed in. Specifically, you get native data types but MSIL functions, unless the function uses something unsupported like function pointers. (Everyday pointers to data are supported.) You can also use &lt;code&gt;#pragma unmanaged&lt;/code&gt; to force native code. Because these files have some native code, they must be built for a specific platform, either x86 or x64.&lt;/p&gt;

&lt;p&gt;The /clr:pure option does what it sounds like: it gives you a file of entirely MSIL. Nonetheless, it must be built for either x86 or x64. This option is said to be equivalent to a C# project with unsafe code.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://msdn.microsoft.com/en-us/library/31zwwc39%28VS.80%29.aspx"&gt;Microsoft’s documentation on the /clr and /clr:pure flags&lt;/a&gt; says that they can only produce x86 files, but my tests prove this to be false. If I build the C++ version of the WOW64-tester, using x64 and /clr compilation options, then it reports that it is not running in WOW64. So apparently you can in fact produce x64 applications with these options.&lt;/p&gt;

&lt;p&gt;The last one, /clr:safe, enforces code that is verifiably type-safe—but I’m not sure what all that means. I’ve read that if you use this option, your file can run on any platform, like building as Any CPU in C#. This option requires that you use Microsoft’s C++/CLI language, formerly known as Managed C++. I know nothing about this, but people say it’s virtually a new language. I tried to build a Hello World app with &lt;code&gt;printf&lt;/code&gt; and got innumerable compile errors, so I wasn’t able to run any tests on what this option produces.&lt;/p&gt;

&lt;p&gt;There is also a /clr:oldSyntax option, which is like /clr:safe but with the old Managed C++ syntax rather than C++/CLI. Since Managed C++ is deprecated, I’m not sure why you’d use this for new code.&lt;/p&gt;

&lt;p&gt;I don’t know what the /clr* options mean for P/Invoke. If I build a dll with /clr or /clr:pure, does that mean I can call its exported functions from C# without a &lt;code&gt;DllImport&lt;/code&gt; statement? I haven’t tried. Using &lt;code&gt;DllImport&lt;/code&gt; on these dlls doesn’t cause problems, though.&lt;/p&gt;

&lt;p&gt;You can use a tool called &lt;a href="http://msdn.microsoft.com/en-us/library/ds03hhk8%28VS.80%29.aspx"&gt;dumpbin&lt;/a&gt; to see which /clr options were used to produce a given file. Dumpbin comes with Visual Studio and runs from the command-line:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;dumpbin /CLRHEADER myapp.exe&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This will print (among other things) a &lt;code&gt;Flags&lt;/code&gt; value, which is 0 if the file was build with /clr, 1 with /clr:safe, and 3 with /clr:pure.&lt;/p&gt;

&lt;p&gt;I’m also curious about the interaction between WOW64 and the CLR. If I run a 32-bit C# app on x64, then which comes first: WOW64 or the CLR? Is there a 64-bit CLR that can JIT-compile to either 32- or 64-bit code? Or do I have two CLRs, one for 32 bits and one for 64, and the former runs under WOW64? I suspect the answer is the latter, but I’m not sure how to tell. Either way my code is running in WOW64, so the check I described above won’t tell me anything.&lt;/p&gt;

&lt;p&gt;I created a table to keep track of the data from all my tests. Here it is:&lt;/p&gt;
&lt;table&gt;
	&lt;tr&gt;
		&lt;th&gt;exe&lt;/th&gt;
		&lt;th&gt;machine type&lt;/th&gt;
		&lt;th&gt;binary contents&lt;/th&gt;
		&lt;th&gt;managed?&lt;/th&gt;
		&lt;th&gt;contains assembly?&lt;/th&gt;
		&lt;th&gt;can run on x86?&lt;/th&gt;
		&lt;th&gt;can run on x64?&lt;/th&gt;
		&lt;th&gt;can use x86 C# dll?&lt;/th&gt;
		&lt;th&gt;can use x64 C# dll?&lt;/th&gt;
		&lt;th&gt;can use "Any CPU" C# dll?&lt;/th&gt;
		&lt;th&gt;can use x86 C++ native dll?&lt;/th&gt;
		&lt;th&gt;can use x64 C++ native dll?&lt;/th&gt;
		&lt;th&gt;can use x86 C++ /clr dll?&lt;/th&gt;
		&lt;th&gt;can use x64 C++ /clr dll?&lt;/th&gt;
		&lt;th&gt;can use x86 C++ /clr:pure dll?&lt;/th&gt;
		&lt;th&gt;can use x64 C++ /clr:pure dll?&lt;/th&gt;
	&lt;/tr&gt;
	&lt;tr&gt;
&lt;td&gt;x86 C# exe&lt;/td&gt;
&lt;td&gt;i386&lt;/td&gt;
&lt;td&gt;MSIL&lt;/td&gt;
&lt;td&gt;yes&lt;/td&gt;
&lt;td&gt;yes&lt;/td&gt;
&lt;td&gt;yes, in CLR&lt;/td&gt;
&lt;td&gt;yes, in WOW64+CLR&lt;/td&gt;
&lt;td&gt;yes&lt;/td&gt;
&lt;td&gt;no&lt;/td&gt;
&lt;td&gt;yes&lt;/td&gt;
&lt;td&gt;yes&lt;/td&gt;
&lt;td&gt;no&lt;/td&gt;
&lt;td&gt;yes&lt;/td&gt;
&lt;td&gt;no&lt;/td&gt;
&lt;td&gt;yes&lt;/td&gt;
&lt;td&gt;no&lt;/td&gt;
&lt;/tr&gt;
	&lt;tr&gt;
&lt;td&gt;x64 C# exe&lt;/td&gt;
&lt;td&gt;x64&lt;/td&gt;
&lt;td&gt;MSIL&lt;/td&gt;
&lt;td&gt;yes&lt;/td&gt;
&lt;td&gt;yes&lt;/td&gt;
&lt;td&gt;no&lt;/td&gt;
&lt;td&gt;yes, in CLR&lt;/td&gt;
&lt;td&gt;no&lt;/td&gt;
&lt;td&gt;yes&lt;/td&gt;
&lt;td&gt;yes&lt;/td&gt;
&lt;td&gt;no&lt;sup&gt;2&lt;/sup&gt;
&lt;/td&gt;
&lt;td&gt;yes&lt;/td&gt;
&lt;td&gt;no&lt;/td&gt;
&lt;td&gt;yes&lt;/td&gt;
&lt;td&gt;no&lt;/td&gt;
&lt;td&gt;yes&lt;/td&gt;
&lt;/tr&gt;
	&lt;tr&gt;
&lt;td&gt;"Any CPU" C# exe&lt;/td&gt;
&lt;td&gt;i386&lt;/td&gt;
&lt;td&gt;MSIL&lt;/td&gt;
&lt;td&gt;yes&lt;/td&gt;
&lt;td&gt;yes&lt;/td&gt;
&lt;td&gt;yes, in CLR&lt;/td&gt;
&lt;td&gt;yes, in CLR&lt;/td&gt;
&lt;td&gt;only on x86&lt;sup&gt;1&lt;/sup&gt;
&lt;/td&gt;
&lt;td&gt;only on x64&lt;/td&gt;
&lt;td&gt;yes&lt;/td&gt;
&lt;td&gt;only on x86&lt;sup&gt;1&lt;/sup&gt;
&lt;/td&gt;
&lt;td&gt;only on x64&lt;/td&gt;
&lt;td&gt;only on x86&lt;/td&gt;
&lt;td&gt;only on x64&lt;/td&gt;
&lt;td&gt;only on x86&lt;/td&gt;
&lt;td&gt;only on x64&lt;/td&gt;
&lt;/tr&gt;
	&lt;tr&gt;
&lt;td&gt;x86 C++ exe&lt;/td&gt;
&lt;td&gt;i386&lt;/td&gt;
&lt;td&gt;asm&lt;/td&gt;
&lt;td&gt;no&lt;/td&gt;
&lt;td&gt;no&lt;/td&gt;
&lt;td&gt;yes, natively&lt;/td&gt;
&lt;td&gt;yes, in WOW64&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;/tr&gt;
	&lt;tr&gt;
&lt;td&gt;x64 C++ exe&lt;/td&gt;
&lt;td&gt;x64&lt;/td&gt;
&lt;td&gt;asm&lt;/td&gt;
&lt;td&gt;no&lt;/td&gt;
&lt;td&gt;no&lt;/td&gt;
&lt;td&gt;no&lt;/td&gt;
&lt;td&gt;yes, natively&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;/tr&gt;
	&lt;tr&gt;
&lt;td&gt;x86 C++ /clr exe&lt;/td&gt;
&lt;td&gt;i386&lt;/td&gt;
&lt;td&gt;MSIL, mostly&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;td&gt;yes, in CLR&lt;/td&gt;
&lt;td&gt;yes, in WOW64+CLR&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;/tr&gt;
	&lt;tr&gt;
&lt;td&gt;x64 C++ /clr exe&lt;/td&gt;
&lt;td&gt;x64&lt;/td&gt;
&lt;td&gt;MSIL, mostly&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;td&gt;no&lt;/td&gt;
&lt;td&gt;yes, in CLR&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;/tr&gt;
	&lt;tr&gt;
&lt;td&gt;x86 C++ /clr:pure exe&lt;/td&gt;
&lt;td&gt;i386&lt;/td&gt;
&lt;td&gt;MSIL&lt;/td&gt;
&lt;td&gt;yes&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;td&gt;yes, in CLR&lt;/td&gt;
&lt;td&gt;yes, in WOW64+CLR&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;/tr&gt;
	&lt;tr&gt;
&lt;td&gt;x64 C++ /clr:pure exe&lt;/td&gt;
&lt;td&gt;x64&lt;/td&gt;
&lt;td&gt;MSIL&lt;/td&gt;
&lt;td&gt;yes&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;td&gt;no&lt;/td&gt;
&lt;td&gt;yes, in CLR&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;td&gt;?&lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;
&lt;p&gt;&lt;sup&gt;1&lt;/sup&gt;&lt;/p&gt;

&lt;p&gt;There may be some option like the linker’s /CLRHEADER for C# apps.&lt;/p&gt;

&lt;p&gt;&lt;sup&gt;2&lt;/sup&gt;&lt;/p&gt;

&lt;p&gt;Can’t run on x86, and won’t be in WOW64 on x64. But see note 1.&lt;/p&gt;

&lt;p&gt;There are still some gaps in this table. I’m not that concerned about the interactions between C++ exes and C++ dlls, so I’ve left those cells blank. I’ve also left some cell blanks regarding when C++ files are managed/unmanaged and when they contain an assembly. If I figure any of this out, I’ll update the table.&lt;/p&gt;

&lt;p&gt;One final notable tool is ildasm (IL-disassembler), which also comes with Visual Studio. This lets you inspect the IL of an exe or dll. Most of it is over my head, but it’s intetesting to see what your code becomes.&lt;/p&gt;
</content>
  </entry>
  <entry>
    <id>tag:illuminatedcomputing.com,2010-01-31:/posts/2010/01/dll-inspector/</id>
    <title type="html">DLL Inspector</title>
    <published>2010-01-31T00:00:00Z</published>
    <updated>2010-01-31T00:00:00Z</updated>
    <link rel="alternate" href="https://illuminatedcomputing.com/posts/2010/01/dll-inspector/" type="text/html"/>
    <content type="html">
&lt;p&gt;Since I’ve been experimenting with 32- and 64-bit DLLs, along with the different /clr compiler options, I decided to write a quick utility to help me see how they differ. It has a small GUI:&lt;/p&gt;

&lt;p&gt;&lt;a href="/img/dllinfo-screenshot.png"&gt;&lt;img alt="" class="alignnone size-full wp-image-64" height="300" src="/img/dllinfo-screenshot.png" title="dllinfo-screenshot" width="300"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I used this utility to build a bunch of dlls with various compiler options. I’ll post about that shortly. Here is the code for DllInfo, if anyone is interested. There is still some work to do, but what I’ve got so far served my purpose well enough:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using System.Runtime.InteropServices;
using System.IO;

// TODO: About DllInfo...
// better display in currentFileBox

// Based on Kris Stanton's code at http://blogs.msdn.com/kstanton/archive/2004/03/31/105060.aspx

namespace DllInfo
{
    public enum MachineType
    {
        Native = 0,
        I386 = 0x014c,
        Itanium = 0x0200,
        x64 = 0x8664
    }

    [StructLayout(LayoutKind.Explicit)]
    public struct IMAGE_DOS_HEADER
    {
        [FieldOffset(60)]
        public int e_lfanew;    // byte offset to the NT header
    }

    [StructLayout(LayoutKind.Explicit)]
    public struct IMAGE_NT_HEADERS32
    {
        [FieldOffset(0)]
        public uint Signature;
        [FieldOffset(4)]
        public IMAGE_FILE_HEADER FileHeader;
        [FieldOffset(24)]
        public IMAGE_OPTIONAL_HEADER32 OptionalHeader;
    }

    [StructLayout(LayoutKind.Explicit)]
    public struct IMAGE_NT_HEADERS64
    {
        [FieldOffset(0)]
        public uint Signature;
        [FieldOffset(4)]
        public IMAGE_FILE_HEADER FileHeader;
        [FieldOffset(24)]
        public IMAGE_OPTIONAL_HEADER64 OptionalHeader;
    }

    public struct IMAGE_FILE_HEADER {
        public ushort Machine;
        public ushort NumberOfSections;
        public ulong TimeDateStamp;
        public ulong PointerToSymbolTable;
        public ulong NumberOfSymbols;
        public ushort SizeOfOptionalHeader;
        public ushort Characteristics;
    }

    [StructLayout(LayoutKind.Explicit)]
    public struct IMAGE_OPTIONAL_HEADER32
    {
        [FieldOffset(0)]
        public ushort Magic;
        [FieldOffset(208)]
        public IMAGE_DATA_DIRECTORY DataDirectory;
    }

    [StructLayout(LayoutKind.Explicit)]
    public struct IMAGE_OPTIONAL_HEADER64
    {
        [FieldOffset(0)]
        public ushort Magic;
        [FieldOffset(224)]
        public IMAGE_DATA_DIRECTORY DataDirectory;
    }

    public struct IMAGE_DATA_DIRECTORY
    {
        public uint VirtualAddress;
        public uint Size;
    }

    public partial class DllInfoForm : Form
    {
        String currentDll = null;
        bool validDll = false;
        String machineType = null;
        bool isManaged = false;
        int moduleCount;
        bool hasAssembly;

        public DllInfoForm()
        {
            InitializeComponent();
            infoPanel.Paint += new PaintEventHandler(panelOnPaint);
        }

        void panelOnPaint(object obj, PaintEventArgs pea)
        {
            Graphics g = pea.Graphics;
            Brush brush = new SolidBrush(ForeColor);

            g.DrawString("valid?: ", Font, brush, 0, 0);
            g.DrawString(currentDll == null ? "" : validDll.ToString(), Font, brush, 100, 0);
            g.DrawString("machine: ", Font, brush, 0, 20);
            g.DrawString(machineType, Font, brush, 100, 20);
            g.DrawString("managed?: ", Font, brush, 0, 40);
            g.DrawString(validDll ? isManaged.ToString() : "", Font, brush, 100, 40);
            g.DrawString("has assembly?: ", Font, brush, 0, 60);
            g.DrawString(validDll ? hasAssembly.ToString() : "", Font, brush, 100, 60);
            g.DrawString("module count: ", Font, brush, 0, 80);
            g.DrawString(validDll ? moduleCount.ToString() : "", Font, brush, 100, 80);
            // TODO: is it IL or binary?
        }

        void updateDisplay() {
            if (currentDll == null)
            {
                currentFileBox.Text = "";
            }
            else
            {
                currentFileBox.Text = currentDll;
            }
            infoPanel.Invalidate();
        }

        private void chooseFile(object sender, EventArgs ea)
        {
            OpenFileDialog d = new OpenFileDialog();
            d.Filter = "dll and exe files (*.dll, *.exe)|*.dll;*.exe|All files (*.*)|*.*";
            d.Title = "Select a dll";
            if (d.ShowDialog() == DialogResult.OK)
            {
                currentDll = d.FileName;
                try
                {
                    loadDll(currentDll);
                    updateDisplay();
                }
                catch (BadImageFormatException)
                {
                    MessageBox.Show("bad image format exception");
                }
            }
        }

        public void loadDll(String dll)
        {
            byte[] data = new byte[4098];
            FileInfo fi = new FileInfo(dll);
            FileStream f;
            int n;
            ushort m;

            try
            {
                f = fi.Open(FileMode.Open, FileAccess.Read);
                // TODO: better to catch file-opening exceptions and show the user the problem.
            }
            catch
            {
                validDll = false;
                return;
            }

            n = f.Read(data, 0, 4096);
            f.Flush();
            f.Close();
            f.Dispose();

            // We must have read at least far enough to read dos_header-&amp;gt;e_lfanew
            // Marshal.OffsetOf warns that the managed struct offsets may differ from the unmanaged,
            // but this is only true if the data types are not blittable.
            // Since C# lets me obtain points to these structs, I know that they are blittable,
            // so I can disregard the warning about Marshal.OffsetOf.
            if (n &amp;lt; (int)Marshal.OffsetOf(typeof(IMAGE_DOS_HEADER), &amp;amp;quot;e_lfanew&amp;amp;quot;) + sizeof(int))
            {
                validDll = false;
                return;
            }

            unsafe
            {
                fixed (byte* d = data)
                {
                    IMAGE_DOS_HEADER *dos_header = (IMAGE_DOS_HEADER*)d;

                    // Make sure we read enough bytes to follow e_lfanew and read everything else:
                    // Use the 64-bit values since they are a few bytes larger.
                    // If we&amp;amp;#39;re running on 32 bits, there will still be other bits in the dll after the header,
                    // so we won&amp;amp;#39;t reject any false positives.
                    if (n e_lfanew
                        + (int)Marshal.OffsetOf(typeof(IMAGE_NT_HEADERS64), "OptionalHeader") // +24
                        + (int)Marshal.OffsetOf(typeof(IMAGE_OPTIONAL_HEADER64), "DataDirectory") // +224
                        + (int)Marshal.OffsetOf(typeof(IMAGE_DATA_DIRECTORY), "Size")  // +4
                        + sizeof(uint)) // +4
                    {
                        validDll = false;
                        return;
                    }

                    IMAGE_NT_HEADERS32* nt32_header = (IMAGE_NT_HEADERS32*)(d + dos_header-&amp;gt;e_lfanew);

                    m = nt32_header-&amp;gt;FileHeader.Machine;

                    validDll = Enum.IsDefined(typeof(MachineType), (Int32)m);
                    if (validDll)
                    {
                        machineType = ((MachineType)m).ToString();


                        // 0x10b indicates a PE32 assembly
                        // 0x20b indicates a PE32+ assembly (i.e. 64-bit, hence either x64 or Itanium)
                        if (nt32_header-&amp;gt;OptionalHeader.Magic == 0x20b)
                        {
                            isManaged = ((IMAGE_NT_HEADERS64*)nt32_header)-&amp;gt;OptionalHeader.DataDirectory.Size &amp;gt; 0;
                        }
                        else
                        {
                            isManaged = nt32_header-&amp;gt;OptionalHeader.DataDirectory.Size &amp;gt; 0;
                        }
                    }
                }
            }

            if (validDll)
            {
                Assembly a;
                Module mod;
                PortableExecutableKinds peKind;
                ImageFileMachine machine;

                try
                {
                    a = Assembly.LoadFile(dll);
                    hasAssembly = true;
                    moduleCount = a.GetModules().Length;
                    // TODO: sanity check that PEKind matches what we inferred from the binary?
                    /*
                    m = a.GetModules()[0]; // TODO: multi-module assemblies?
                    m.GetPEKind(out peKind, out machine);
                    dllType = peKind.ToString();
                    machineType = machine.ToString();
                      */
                }
                catch (BadImageFormatException)
                {
                    // This is not quite right:
                    // The file may have an assembly but be opened on the wrong platform (32 vs 64 bits).
                    hasAssembly = false;
                    moduleCount = 0;
                }
                catch (FileLoadException)
                {
                    hasAssembly = true;
                    moduleCount = -1;
                }

            }
        }
    }
}&lt;/code&gt;&lt;/pre&gt;
</content>
  </entry>
  <entry>
    <id>tag:illuminatedcomputing.com,2010-01-23:/posts/2010/01/enabling-64-bit-support-in-visual-studio-2008/</id>
    <title type="html">Enabling 64-bit Support in Visual Studio 2008</title>
    <published>2010-01-23T00:00:00Z</published>
    <updated>2010-01-23T00:00:00Z</updated>
    <link rel="alternate" href="https://illuminatedcomputing.com/posts/2010/01/enabling-64-bit-support-in-visual-studio-2008/" type="text/html"/>
    <content type="html">
&lt;p&gt;With all my confusion about 32- vs. 64-bits in C# and C++, I wanted to build some C++ exes and dlls in 64 bits to work out how everything fit together. But it took me a while to figure out how to do this in Visual Studio. For a C# project, there is an easy-to-find option under &lt;code&gt;Build&lt;/code&gt; called &lt;code&gt;Platform Target&lt;/code&gt;, with choices called &lt;code&gt;Any CPU&lt;/code&gt;, &lt;code&gt;x86&lt;/code&gt;, and &lt;code&gt;x64&lt;/code&gt;. But there is nothing quite so evident among the properties for a C++ project.&lt;/p&gt;

&lt;p&gt;To build a 64-bit version for your C++ app, you should open the Properties dialog and then click the &lt;code&gt;Configuration Manager&lt;/code&gt; button in the upper-right corner. Then select the &lt;code&gt;Active Solution Platform&lt;/code&gt; dropdown menu, and choose &lt;code&gt;&amp;lt;New...&amp;gt;&lt;/code&gt;. Select &lt;code&gt;x64&lt;/code&gt;, and request to copy over the old Win32 properties. Now you can build your project for either 32 or 64 bits. Visual Studio maintains separate properties for each. You use the Configuration Manager to set the “Active” platform, which is what actually gets built, but you can adjust the properties of either platform using the &lt;code&gt;Platform&lt;/code&gt; dropdown at the top of the properties dialog.&lt;/p&gt;

&lt;p&gt;Once you’ve enabled both platforms for your project, make sure x64 is set as the active target, and take at look at the x64 properties under &lt;code&gt;Linker:Advanced&lt;/code&gt;. You should see one called &lt;code&gt;Target Machine&lt;/code&gt;, set to &lt;code&gt;MachineX64 (/MACHINE:X64)&lt;/code&gt;. Under the Win32 version, this read &lt;code&gt;MachineX86 (/MACHINE:X86)&lt;/code&gt;, but Visual Studio should have flipped it automatically when you created the x64 target. If not, set it correctly now.&lt;/p&gt;

&lt;p&gt;Note that if you have a mismatch between the Platform and the linker’s setting, you’ll get a build error like this:&lt;/p&gt;
&lt;blockquote&gt;
fatal error LNK1112: module machine type 'X86' conflicts with target machine type 'x64'	&lt;/blockquote&gt;
&lt;p&gt; So you need MachineX86 with a Win32 platform, and MachineX64 with the x64 platform.&lt;/p&gt;

&lt;p&gt;Now you should be able to build both 32- and 64-bit versions of your app!&lt;/p&gt;
</content>
  </entry>
</feed>

