CSharp Puzzles for the Agile – Round 1

For those who have free time on their hands, and who would like to work through some brain twisters, here is a list of C# code snippets for your perusal. See https://www.toptal.com/c-sharp/top-10-mistakes-that-c-sharp-programmers-make for more details.

1.

//=============================================================================

private static void CSharpPuzzle1()
{
    Point point1 = new Point(20, 30);
    Point point2 = point1;
    point2.X = 50;
    Console.WriteLine(point1.X);       // What is the output?
    Console.WriteLine(point2.X);       // What is the output?
    Pen pen1 = new Pen(Color.Black);
    Pen pen2 = pen1;
    pen2.Color = Color.Blue;
    Console.WriteLine(pen1.Color);     // What is the output?
    Console.WriteLine(pen2.Color);     // What is the output?
    Console.WriteLine();
}

2.

//=============================================================================

static Pen pen1;
static Point point1;
public static void CSharpPuzzle2()
{
    Console.WriteLine(pen1 == null); // What is the output?
    Console.WriteLine(point1 == null); // What is the output?
    Console.WriteLine(point1 == default(Point));
    // Note: you can't declare an auto of a value type without an initializer!
    //Point p;
    //p.X = 1;
    Console.WriteLine();
}

3.

//=============================================================================

static void CSharpPuzzle3()
{
    string s = "strasse";

    // What is the output?
    Console.WriteLine(s == "straße");
    Console.WriteLine(s.Equals("straße"));
    Console.WriteLine(s.Equals("straße", StringComparison.Ordinal));
    Console.WriteLine(s.Equals("Straße", StringComparison.CurrentCulture));
    Console.WriteLine(s.Equals("straße", StringComparison.OrdinalIgnoreCase));
    Console.WriteLine(s.Equals("straße", StringComparison.CurrentCulture));
    Console.WriteLine(s.Equals("Straße", StringComparison.CurrentCultureIgnoreCase));
    Console.WriteLine(s == "strasse");
    Console.WriteLine(s.Equals("strasse"));
    Console.WriteLine();
}

4.

//=============================================================================

class Account
{
    [Key]
    public string ID { get; set; }
    public string Status { get; set; }
    public decimal Balance { get; set; }
}

static void CSharpPuzzle4()
{
    List<Account> myAccounts = new List<Account>()
    {
	    new Account() { Status = "active", Balance = 1 },
	    new Account() { Status = "inactive", Balance = 2 },
	    new Account() { Status = "active", Balance = 3 }
    };

    // What is the output?
    {
	    decimal total = 0;
	    foreach (Account account in myAccounts)
	    {
	        if (account.Status == "active")
	        {
		        total += account.Balance;
	        }
	    }
	    Console.WriteLine(total);
    }

    // What is the output?
    {
	    decimal total = myAccounts.Sum((account) => (account.Status == "active") ? account.Balance : 0);
	    Console.WriteLine(total);
    }
}

5.

//=============================================================================

class Accounts : DbContext
{
    public Accounts() : base("Accounts.DbConnection") {}

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
	    Database.SetInitializer<Accounts>(new SocialClubInitializer());
	    base.OnModelCreating(modelBuilder);
    }

    public DbSet<Account> _accounts { get; set; }
}

class SocialClubInitializer : DropCreateDatabaseAlways<Accounts>
{
    protected override void Seed(Accounts context)
    {
	    context._accounts.Add(new Account() { ID = "1", Status = "Active", Balance = 1 }); // Note capital "A"
	    context._accounts.Add(new Account() { ID = "2", Status = "Inactive", Balance = 2 });
	    context._accounts.Add(new Account() { ID = "3", Status = "Active", Balance = 3 }); // Note capital "A"
    }
}

static void CSharpPuzzle5()
{
    Accounts dbc = new Accounts();
    dbc.SaveChanges();
    var count = dbc._accounts.Count();
    {
	    decimal total = dbc._accounts.Sum(
	        (account) => (account.Status == "active") ? 
		    (decimal?) account.Balance :
		    0) ?? 0;
	    Console.WriteLine(total); // What is the output?
    }
}

6.

//=============================================================================

static void CSharpPuzzle6()
{
    int[] a = new int[] {1, 3, 5, 7, 9};
    int sum = a.Sum(); // Where is Sum defined?
    int len = a.Length; // Where is Length defined?
}

7.

//=============================================================================

static void CSharpPuzzle7()
{
    // Which implementation is faster?
    // Which implementation uses more memory?
    { // Implementation A.
	    var before = DateTime.Now;
	    int size = 100000000;
	    bool[] a = new bool[size];
	    for (int i = 1; i < size; ++i) a[i] = a[i - 1];
	    var after = DateTime.Now;
	    Console.WriteLine(a.SizeOf());
	    Console.WriteLine(after - before);
    }
    { // Implementation B.
	    var before = DateTime.Now;
	    int size = 100000000;
	    BitArray a = new BitArray(size);
	    for (int i = 1; i < size; ++i) a[i] = a[i - 1];
	    var after = DateTime.Now;
	    Console.WriteLine(a.SizeOf());
	    Console.WriteLine(after - before);
    }
}

8.

//=============================================================================

class SystemResource : IDisposable
{
    public void Dispose()
    {
        // The implementation of this method not described here.
        // ... For now, just report the call.
        Console.WriteLine(0);
    }
}

static void CSharpPuzzle8()
{
    // What is the output?
    using (SystemResource resource = new SystemResource())
    {
        Console.WriteLine(1);
    }
    Console.WriteLine(2);
    {
        SystemResource leak = new SystemResource();
        Console.WriteLine(3);
    }
    Console.WriteLine(4);
}

9.

//=============================================================================

class B { }
class D1 : B { }
class D2 : B { }

static void CSharpPuzzle9()
{
    try
    {
        B o = new D1();
        D2 c = (D2) o;
    }
    catch (Exception) { Console.WriteLine("Exception1"); }

    try
    {
        B o = new D1();
        D2 d = o as D2;
    }
    catch (Exception) { Console.WriteLine("Exception2"); }
}

10.

//=============================================================================

class CSharpPuzzle10
{
    // What does the compiler output for warnings and errors?
    int myId;
    int Id;
    CSharpPuzzle10(int id)
    {
        this.myId = Id;
    }
}