Skip to content

Instantly share code, notes, and snippets.

@cawhitworth
Last active August 29, 2015 14:23
Show Gist options
  • Save cawhitworth/64a6062ecdcf27b12d09 to your computer and use it in GitHub Desktop.
Save cawhitworth/64a6062ecdcf27b12d09 to your computer and use it in GitHub Desktop.
Fun with constructors
namespace ConstructorFun
{
class ConstructorLoop
{
public ConstructorLoop(int a, int b) : this(a, b, 20)
{ }
public ConstructorLoop(int a, int b, int c) : this(a,b)
{ }
}
class Program
{
static void Main(string[] args)
{
var a = new ConstructorLoop(1,2);
}
}
}
@cawhitworth
Copy link
Author

So, this is totally legit C#, apparently. Not even a compiler warning.

@cawhitworth
Copy link
Author

Oh, even better!

namespace ConstructorFun
{
    class ConstructorLoop
    {

        public static int Counter { get; set; }

        public ConstructorLoop(int a, int b) : this(a, b, 20)
        { }

        public ConstructorLoop(int a, int b, int c) : this(f(a),b)
        { }

        static int f(int f)
        {
            Counter ++;
            if (Counter > 10)
                throw new Exception();
            return f;
        }

        public override string ToString()
        {
            return "Hello world!";
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                var a = new ConstructorLoop(1, 2);
            }
            catch (Exception e)
            {
                // ignored
            }
            finally
            {
                Console.WriteLine(ConstructorLoop.Counter);
            }
        }
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment