Test Yourself on C# Types

I’ve been thinking about writing a technical test for my employer, and thought that I would start by following-up on my last post, and create a basic test on types and how they are passed as parameters.

Here’s the code in full (for a VS2005 Console project):

using System;
using System.Collections.Generic;
using System.Text;

namespace TestUnderstandTypes
{
    class Program
    {
        static void Main(string[] args)
        {
            AClass c = new AClass();
            c.Member = 26;
            DoSomething(c);
            Console.WriteLine(string.Format("Value of c.Member is {0}",
                                            c.Member.ToString()));

            AStruct s = new AStruct();
            s.Member = 26;
            DoSomething(s);
            Console.WriteLine(string.Format("Value of s.Member is {0}",
                                            s.Member.ToString()));

            int[] a = new int[20];
            initA(a);

            DoSomething(a);
            Console.WriteLine(string.Format("Value of a[5] is {0}",
                                            a[5].ToString() ));

            initA(a);

            DoSomethingElse(a);
            Console.WriteLine(string.Format("Value of a[5] is now {0}",
                                            a[5].ToString()));

            Console.Write("nPress a key... ");
            Console.ReadKey();
        }

        static void DoSomething(AClass c)
        {
            c.Member = 42;
        }

        static void DoSomething(AStruct s)
        {
            s.Member = 42;
        }

        static void initA(int[] a)
        {
            for (int i = 0; i < a.Length; i++)
                a[i] = i;
        }

        static void DoSomething(int[] a)
        {
            a[5] = 42;
        }

        static void DoSomethingElse(int[] a)
        {
            a = new int[20];
            for (int i = 0; i < a.Length; i++)
                a[i] = 20 - i;
        }

    }

    public class AClass
    {
        int _member;

        public int Member
        {
            get { return _member; }
            set { _member = value; }
        }
    }

    public struct AStruct
    {
        int _member;

        public int Member
        {
            get { return _member; }
            set { _member = value; }
        }
    }

}

The output looks something like this:

Value of c.Member is ?
Value of s.Member is ?
Value of a[5] is ?
Value of a[5] is now ?

Press a key...

Questions

  1. Fill in the question marks in the output fragment, and explain why.
    Also explain what would happen if the int[] parameter to DoSomethingElse was changed to a ref int[].
  2. Why is it a good idea to use the integerValue.ToString() method in the string.Format arguments?
  3. Suggest some ways that this code could be improved.

The real answers for 1 and 2, and my thoughts for 3 will be in my next post.