Wednesday, June 18, 2008

Control structures in C#

These structures are as follows:

if (expression)

{

statement1...[n]

}

elseif (expression)

{

statement1...[n]

}

.

.

else

{

statement1...[n]

}

Please pay attention to logical operators && and while using then as a expression in if structure because as we explain earlier they won't check the second operand if the first one fulfill the condition.

while (expression)

{

statement1...[n]

}

do

{

statement1...[n]

} while (expression);

In comparison between while and do while , do while will execute the statement at least once.

To explain for stucture we can express an example to clarify it.

for (int i = 1; i < 10;i++ )

{

Console.WriteLine(i);

}

Another control structure is for each. But before we go through it, we should know what arrays are. That's because for each is used only with a of collection entities, collection of data types.

Structure of foreach is as bellow.

foreach (collectionDataType varName in collectionName)

{

statement1…[n];

}

It means that each item in collection will be assigned to varName then the code in the block will be run for varName.

Array

Arrays are of those kinds of variables that are placed in heap memory.(go to first lesson, memory management)

Array is a collection of specific data type. Let's have an example to understand both for each control structure and arrays.

int[] nums = new int [3];

nums[0] = 10;

nums[1] = 15;

nums[2] = 20;

int sum = 0;

foreach (int n in nums )

{

sum = sum + n ;

}

Console.WriteLine("The summary is :{0}" ,sum);

In above code each item in nums is assigned to n and then the code in the block will be run for each item.

Break and Continue

It's time now to talk about break and continue. Remember that, these two statements are using in loop structures. Like for, while, do while and …. Let's see the usage of them in an example.

If you run the following code snippet you will see that when i =5 the code will stop. It means although i is less that 100 but the rest of code won't execute.

for (int i = 1; i < 100; i++)

{

if (i%5 == 0)

{

Console.WriteLine("Hope!");

break ;

}

Console.WriteLine(i);

}

The result will be as follow

Figure 4

But if you change the code like this:

for (int i = 1; i < 100; i++)

{

if (i%5 == 0)

{

Console.Write Line("Hope!");

continue ;

}

Console.WriteLine(i);

}

Instead of each number that is dividable to 5 the word "Hope" will be printed. The result of running the above code snippet is shown in figure 5

Figure 5

Note: You are not allowed to change the value of the counter in the foreach control structure. This is a read only value. It means you can not change the value of i in the code above.

GoTo:

Probably no other construct in programming history is as maligned as the goto statement. The problem with using goto is use of it in inappropriate places.

The structure of goto is

goto lableName;

lableName:

Statement1…[n];

It is hardly recommended to use goto because it reduces the performance of the application, except in some cases that it will increase the performance. Using goto in nested loops that break can't help you will be very handy.

Switch case

Another control structure is switch with the following structure

 switch (expression)
{  
   case constant-expression:
        statement
        jump-statement
    case constant-expressionN:
        statementN
    [default]
}

In this structure as you can see if you write even one statement you should have a jump-statement that can be break or got otherwise you as a programmer will face an compile time error indicating that you lost a jump-statement. Don't forget to define break in default case. Let's explain the structure in a sample code.

Console.WriteLine ("Enter 10,20 or 30");

int a = Convert.ToInt32 ( Console.ReadLine());

switch (a)

{

case 10:

case 20:

Console.WriteLine("I have more than {0} books", a);

break;

case 30:

Console.WriteLine("I have {0} books", a);

break;

}

In this case you won't get a compiler error because of not having break in the first case statement. The reason is you don't write any code for that specific case statement. This means compiler will execute codes till it arrives to a break or goto. If a user enters 10 as the value or 20 he will receive similar out puts.

But what if you want the compiler execute first and second statements that are in case 10 and 20 if user_entered_value is 10 and execute statement in second case if user_entered_value is 20. You simply can modify the code as bellow using goto.

Console.WriteLine ("Enter 10,20 or 30");

int a = Convert.ToInt32 ( Console.ReadLine());

switch (a)

{

case 10:

case 20:

Console.WriteLine("I have more than {0} books", a);

break;

case 30:

Console.WriteLine("I have {0} books", a);

break;

}

please pay attention to the out put with different entered_values.

Figure 6- User entered 10

Figure 6- User entered 20

"Thanks To Azadeh for writing this post"

Tuesday, June 17, 2008

Access master page members from a page

download the source code

Sometimes we need define a property or a method in a masterpage and we need access to that property or method in pages that are using that masterpage. To do this we have two choices.

1- Using FindControl (this.Master.FindControl("usercontrolid"))

2- Using this.Master.YourProperty

The first one is not type safe so you could misspelled a property name then you will get null so this approach is error porn. Furthermore, the control should be cast to a valid control. Also you cannot access property by this approach but you can access to controls in masterpage. However, it does not need any other effort.

The second one is type safe, access to masterpage properties is possible and there is no need for casting. However, it needs that the control be defined at least internal and you need define the master type in your page. Then compiler can detect that master page property and it allows you to access to those property through intelisence.

Let's see an example: we have a Label and image in our masterpage and we have some methods in our master page. We need to call these methods from page that is using these masterpage. Also we have a property in master page that we need to have access in our page. Take a look at this:

This is the master page html code:

This master page properties and methods

public Label TitleLable

{

get

{

return LabelTitle;

}

}

public void ShowImage()

{

Image1.Visible = true;

}

public void HideImage()

{

Image1.Visible = false;

}

Then we create a page that is using this masterpage. And this is the html code:

Important: in this code we defined a mastertype directive to notify compiler that we are using these masterpages then if you compile and try to access masterpage methods and properties you can see them.

Take a look to the code behind of the page. As you see we implemented both way. I highly recommend the second way. Remember the first way does not force you to define mastertype in the page. While, second way need the mastertype directive in html code of the page:

protected void ButtonChangeTitle_Click(object sender, EventArgs e)

{

//first way

//Label lbl = Master.FindControl("LabelTitle") as Label;

//lbl.Text = "New Title is Assigned";

//second way

Master.TitleLable.Text = "New Title is Assigned";

}

protected void ButtonHideImage_Click(object sender, EventArgs e)

{

//first way

//Image img = Master.FindControl("Image1") as Image;

//img.Visible = false;

//second way

Master.HideImage();

}

protected void ButtonShowImage_Click(object sender, EventArgs e)

{

//first way

//Image img = Master.FindControl("Image1") as Image;

//img.Visible = true;

//second way

Master.ShowImage();

}

As I said before I highly recommend the second way. Let's review the steps:

1- Create a master page

2- Define some public properties and methods in masterpage

3- Create a page using the master page

4- Define the mastertype directive in page

5- You can access masterpage public properties and method through Master object in the page