Saturday, June 10, 2006

C# Amusements

Is not really about VoIP or any other gadget but the subject may be still interesting to C# programmers out there. The following are a few C# tricky questions that you may also view them as programmer’s amusements.

1. Supposing you have a Windows Forms applications with 3 buttons, the event handlers for these buttons containing the following code, please tell what the result of pressing these buttons is.

private int m_p1;
private int m_p2;

public int p1
{
get { MessageBox.Show("get_p1"); return m_p1; }
set { m_p1 = value; }
}

public int p2
{
get { MessageBox.Show("get_p2"); return m_p2; }
set { m_p2 = value; }
}



private void button1_Click(object sender, System.EventArgs e)
{
this.p1 = 3;
this.p2 = 3;
}

private void button2_Click(object sender, System.EventArgs e)
{
this.m_p1 = this.m_p2 = 3;
}

private void button3_Click(object sender, System.EventArgs e)
{
this.p1 = this.p2 = 3;
}



2. Tell if the following code compiles and if runs what is the result. Please note that method DoSomething2 is private.

Test t = new Test();
t.DoSomething1();



public class Test
{
public void DoSomething1()
{
Test tst = new Test();
tst.DoSomething2();
}

private void DoSomething2()
{
MessageBox.Show("Hello");
}
}


3. Does the following code compiles and runs correctly?

private void DoSomething(int Count, string Name)
{
MessageBox.Show("1");
}

private void DoSomething(int Count, string[] Names)
{
MessageBox.Show("2");
}

private void button3_Click(object sender, System.EventArgs e)
{
DoSomething(3, null);
}


4. Tell is the following code is a valid C# snippet. If yes find out the result of running this code.

private void button1_Click(object sender, System.EventArgs e)
{
string @s1 = "STARLIMS";
string @s2 = "Corp.";

string u\u00731 = "Microsoft";
string u\u00732 = "Corp.";

MessageBox.Show(\u00731 + \u00732);
}


5. What’s the effect of executing the following code?

private void uiButton2_Click(object sender, System.EventArgs e)
{
int a = 2;
string b = "abc";

MessageBox.Show(a + b);
}


6. Is the following text a valid C# code? If yes what’s the meaning?

private void button1_Click(object sender, System.EventArgs e)
{
@class("abc");
}


… what about this one?

private void button1_Click(object sender, System.EventArgs e)
{
@return s;
}


Don’t hesitate to leave a comment with your answers to these questions.

No comments: