the static class in C# 2.0 is better than you think!

Fully unrelated to Hatteras, but a C# developer whohas been playing around with the beta was attempting to point out (incorrectly that the "static" modifier to a class was just syntax sugar and no better than making a private default constructor that was never called from the class itself (perhaps one that just did a "throw new NotSupportedException();")  Not that it's a huge deal or a normal situation (priv requirements being what they are, IIRC), but a static class is indeed better for preventing instantiation.  Others have already shown this (and I intended to just link to one of them) but my google karma must have been running low today, so here's a quick little proof:

using System;

using System.Reflection;

public class Program


    static void Main(string[] args)


        Type ncType = typeof(NeverConstructed);

        ConstructorInfo constructor = ncType.GetConstructor(

            BindingFlags.CreateInstance |

                BindingFlags.NonPublic |





        constructor.Invoke(new object[0]);



public class NeverConstructed


    private NeverConstructed()


        Console.WriteLine("NeverConstructed got constructed!");




As you'd imagine, a static class would never allow the above - "error CS0710: Static classes cannot have instance constructors".  Of course, I hesitate to post this because of the usual set of people that freak out as if the above were some kind of security hole (as they typically do when the above is presented to .NET user groups), but just as people learn to actually read dialogs before click Ok (IMHO :), developers need to learn that "private" doesn't mean "secure and safe from the eyes of others" - if you need to protect the data, use the Data Protection API :)  I'm sure I'll get some good comments on this one :)


On an even more unrelated note, if you haven't already, make sure to check out the Power Collections spec - there's some very promising work that Peter (rss) is doing there - very exciting stuff!  I had gotten spoiled with a lot of the stuff in the Jakarta Project's Commons Collections in my work past, so this is good to see developing.