Parameter Passing Quiz :)

Ok, again posting after a long time.

Predict the output of the following code, the contains 3 sets of function calls, each set contains one call by value and one by reference, but the object being passed everytime is a reference type. It is recommended that you do not run the code, just predict the output.

StringBuilder used in the code is a class and is a reference type.

Also explain your answers.

class Class1

{

static void Main(string[] args)

{                

            StringBuilder str;

// Set 1

            str = new StringBuilder(“Types”);

            CrazyFunction1(str);

            Console.WriteLine(str.ToString());

            str = new StringBuilder(“Types”);

            CrazyFunction2(ref str);

            Console.WriteLine(str.ToString());

// Set 2

            str = new StringBuilder(“Types”);

            CrazyFunction3(str);

            Console.WriteLine(str.ToString());

            str = new StringBuilder(“Types”);

            CrazyFunction4(ref str);

            Console.WriteLine(str.ToString());

//Set 3

            str = new StringBuilder(“Types”);

            CrazyFunction5(str);

            Console.WriteLine(str.ToString());

            str = new StringBuilder(“Types”);

            CrazyFunction6(ref str);

            Console.WriteLine(str.ToString());

            Console.ReadLine();

      }

private static void CrazyFunction1(StringBuilder x)

      {

            x = null;

      }

private static void CrazyFunction2(ref StringBuilder x)

{

            x = null;

      }

private static void CrazyFunction3(StringBuilder x)

      {

            x.Append(” are crazy”);

      }

private static void CrazyFunction4(ref StringBuilder x)

      {

            x.Append(” are crazy”);

      }

private static void CrazyFunction5(StringBuilder x)

      {

            x = new StringBuilder(“crazy”);

      }

private static void CrazyFunction6(ref StringBuilder x)

      {

            x = new StringBuilder(“crazy”);

      }

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s