Sunday, November 22, 2009
Back to Basics: Looping
Pretty soon after learning conditional statements comes looping. Looping can be used to scan through a recordset, or to add items to a drop down or any number of things really. Looping is vital to almost any program. Today we will learn how to use for loops and while loops in both C# and VB.
For-Loop
In both C# and VB the for loop can come in two flavors. The more traditional what I will call the counting for loop, and a for each loop which will allow you to loop through a collection or enumeration of things.
First we will start off with the counting for loop. There are three main parts to this for loop. First is the counter and it's initialization. You can either define this outside of the loop and just reference it in the loop, or you can define it inline with the loop. This is the the method I prefer since the scope of the variable is localized to the for loop. Traditionally the counter variables are 'i', 'j', or 'k'. There is nothing wrong with using other variable names, but you will see these 3 used all the time. More often than not you will see 'i' being the most prevalent.
The second part is the ending criteria such as an upper or lower bound, it is essentially how many times the loop will execute. This is a very important piece because if you don't have it then you will enter into an infinite loop in which there is no way your program will exit until you run out of memory or hit the upper bound of the data type you are using (both are bad things). Since this is tested at the beginning of each iteration this is called a pre-test loop.
Lastly we define how are are going to increment our counter. Many times this is just up by one each time or down by one. But you can use any increment you wish. The increment happens after the end of the loop.followed by the check of the counter. If the ending criteria is not met the loop will execute again.
In this example we are just going to loop 10 times writing out to the screen the value of i each time
C#
//Example 1
for (int i = 0; i < 10; i++) {
Response.Write("i=" + i.ToString() + "<br/>");
}
//Example 2
int i;
for (i = 0; i < 10; i+=2) {
Response.Write("i=" + i.ToString() + "<br/>");
}
You can see how I defined the variable 'i' inside the for loop in the first example. In the second I declared the variable outside of the loop. Both are valid, and it is just personal preference. Just remember that the scope on each variable is different.
In the second example above we are incrementing by 2 each time through the loop. The += notation is the same thing as writing out the full expressoin i = i+2. It just makes the whole thing easier to read.
In VB.Net if you are going to increment by 1 each time around you do not need to define the last piece of the loop, it is built in. So in example 1 below we are just going to count up by one. In example 2 we will increment by 2 as before.
VB
//Example
For i As Integer = 0 To 10
Response.Write("i=" & i & "<br/>")
Next
//Example 2
For i As Integer = 0 To 10 Step 2
Response.Write("i=" & i & "<br/>")
Next
So as you can see in Example 2 using the step clause in VB will allow you to change what you increment (or step) by.
The next type of For loop is the for each, which is very useful in stepping though a collection of objects. For example, lets assume we have a collection, addressBook, of people using the class (person) we have been using in the past 2 posts. The examples are just going to loop through all of the items in the collection. Note how we do not have to declare a counter. .Net will handle fetching each item and knowing when to stop. This loop can be re-written into a counting for loop very easily. I would be willing to say that each foreach loop could be re-written as a counting for loop, but the reverse isn't true. I'm not positive on that, but I can't think of any examples to prove me wrong, if you can think of one put it in the comments below.
C#
foreach (person peep in addressBook) {
Response.Write(peep.LastName);
}VB
For Each peep As person In addressBook
Response.Write(peep.LastName)
Next
As you can see the syntax is almost identical between the two languages.
While Loops
While have the same purpose as a for loop, and they can be swapped in almost any case, but sometimes it just makes more sense to use a while loop instead of a for loop.
For example, lets say we have a loop that we really have no way of knowing how many times the loop would need to run. A great example of this is while reading a file from disk. We want to keep looping until we hit the end of file (EOF) character. I am sure you could probably find out the length of the file, divide the bytes and use a for loop, but it just feels better to use a while loop. After programming for a while you will get a good feel of when to use a while loop and when to use a for.
The first example, is just re-writing the counting loop from above just to show you how it is done. The second example is reading from an OracleDataReader. I am not going to show the opening of the data reader and all that, but I am just going to loop through it for you and am going to fill our addressBook from before. I am going to use some newer notation (.Net 3.5) to make the code a bit shorter for the initialization of the person object.
C#
//Example 1
int i;
while (i < 10) {
Response.Write("i=" + i.ToString());
i++;
}
//Example 2
while (reader.HasRows) {
person peep = new person { FirstName = reader["FirstName"], LastName = reader["LastName"], Age = reader["Age"] };
addressBook.Add(peep);
}
So those are your basic loops. There is one more type of loop that can be used the do-while. But haven't used that in many years and is only used in a few cases. The difference being the compiler will check the condition at the end of the loop instead of at the beginning, so your loop will always execute at least once, this is called a post test loop.
And a special thanks to
Brent for guest editing this post
Labels: .NET, Back to Basics
posted by Tom Becker at
|

Monday, November 9, 2009
Back to Basics: Conditional Statements
This is the second in my Back to Basics series, and this time we are going way back. Conditional statements are some of the very first things you learn in any introductory programing class. In this post I will show you the C# and VB syntax for if, if/else, and switch statements.
If-statement
We will start off with the simplest of conditional statements, the if-statement. This is just simple boolean logic that will evaluate true or false. If the result is true, it will execute the block, if false it will skip it. In this example we will check to see if a person is over the age of 21. We will be using the same person class as in my last
postC#
if (myPerson.Age >= 21)
canDrink = true; //Whatever logic you want
Notice that in C# you can omit the curly braces ({}) if the logic under the if statement is one line long. If it is longer than one line you must use the braces. If you omit those, then the line directly beneath the if statement will be the only one evaluated on a conditional basis the rest of the statements will always be executed.
However in the VB.Net syntax you must have a closing End If, even if the statement is a single line.
VB
If myPerson.Age >= 21 Then
canDrink = true
End If
If/Else
The next example is of an if/else statement. The same rules apply as before, we are just extending it a bit. You can chain together as many if/else statements as you wish, just by adding more conditions. However all of the conditions must before the else, with the else being the final statement (if needed, don't have to have an else).
Once the compiler finds a match for your statement it will not execute any more of the statements in your if/else block. This lets the compiler be more efficient.
C#
if (myPerson.Age < 18)
canDrink = canVote = false;
else if (18 <= myPerson.Age < 21) {
canVote = true;
canDrink = false;
}
else {
canDrink = canVote = true;
}
Note in this example that I mixed my curly braces. First condition I didn't need them since I had one line. Second one I did since I have more than one line. And the third I didn't need them but put them anyway.
VB
If myPerson.Age < 18 Then
canVote = canDrink = False
ElseIf 18 <= myPerson.Age < 21 Then
canVote = True
canDrink = False
Else
canVote = canDrink = True
End If
Switch Statement
The switch statement is a little more complicated than the if and if/else statements but it can be very useful and make your code look cleaner in a lot of places. They can be very useful when evaluating enumerations. In the example below lets assume that our person class has an enumeration of hair colors called (strangely) HairColors. So lets use an switch statement to evaluate our public property hair, and do some logic based on hair color. If the hair color is not in our list the default case will be evaluated. I realize that since we are using an enum we would never evaluate the default case, but just bear with me.
C#
switch (myPerson.hair) {
case HairColors.brown:
//You are a brunette
break;
case HairColors.blonde:
// you are blonde, duh
break;
case HairColors.red:
//You are a redhead
break;
case HairColors.black:
//You have black hair
break;
default:
//You have colorful hair
break;
}You must use the break statement to end each specific case. This will exit you out of the enclosing block, in this case the switch. The break statement can be used in any control flow statement, and it will have the same effect. In the switch statement though it is required, and the compiler will throw an error if you omit this step.
VB
Select Case myPerson.hair
Case HairColors.brown
'You are a brunette
Case HairColors.blonde
' you are blonde, duh
Case HairColors.red
'You are a redhead
Case HairColors.black
'You have black hair
Case Else
'You have colorful hair
End Select
In VB, the switch statement is known as a Select Case, and as you can see by the syntax it is very similar to C# other than the naming. In this case however, you do not need to include the break statement, the flow will stop when it hits the next case keyword.
As a bonus I will give you one more statement called the ternary operator. This works very well in C# because of
short-circuiting, but in VB you have to be careful because VB won't short circuit.
You can use the ternary operator to evaluate something and assign a value on one line. You can easily re-write it to be an if/else statement. Lets re-write our first statement using a ternary operator. The first part is your condition. So in this case we are checking to make sure person is over 21. After the question mark is the true part of the statement and the last is the false.
C#
canDrink = myPerson.Age >= 21 ? true : false;
VB
canDrink = IIf(myPerson.Age >= 21, True, False)
The syntax is very similar, however this isn't a true ternary operator since we are calling a function (iif), but it functions almost exactly the same. The difference being that in VB the second part of the statement (the false section) will still be evaluated. In this case it wouldn't matter if it is evaluated since nothing can go wrong.
Check here for some other reading on the subject of VB and iif.
Conclusion
So there are your basic control flow and conditional statements. I hope this was useful, and good luck.
Labels: .NET, Back to Basics
posted by Tom Becker at
|

Thursday, November 5, 2009
Back to Basics: Parameterizing Inline SQL
Things have been a bit slow with any interesting project work and I don't want this blog to fall
even more stagnant . So I am going to be writing a new series called "Back to Basics" containing best practices and some basic code references aimed at newer coders.
There are some situations in which you cannot use stored procedures in order to handle all of your data access. Some cases it is just because of the architecture where you are at, other times it is because you are building the SQL at run time (this still can be done in both P/L or T-SQL but in this case we are going to write it inline).
But no matter what the circumstance, it is still good practice to parameterize your statements. This can help with style as well as helping to protect against
SQL Injection (Wikipedia).
We will take a normal inline SQL statement and convert it to a parameterized statement. We will start with this.
public void Save() {
string sql = "INSERT INTO People (First_Name, Last_Name, Age) VALUES (\"" + this.FirstName + "\", \"" + this.LastName +
"\", \"" + this.Age + "\");";
using (OracleConnection conn = new OracleConnection("connstring"))
using (OracleCommand comm = new OracleCommand(conn, sql)) {
comm.CommandType = CommandType.Text;
comm.ExecuteNonQuery();
}
}This will work as is, and technically is correct. However, the readability goes out the window. With all the escape characters and everything in that statement it becomes hard to read very quickly. This is also a very small insert statement. Imagine a larger table with 15-20 rows. The statment would become huge and debugging would become hard if you mistyped something, so along with the readability, scaleability is bad as well.
So lets take that statement and parameterize it. This adds to the number of lines of code, but in this case it is well worth it. We take out all of the items in the VALUES clause and replace them with identifiers, much like you would if you were writing a full stored procedure. Then you can add the parameters to the command object. With this you can specify data types and sizes to even further restrict the data entered to help make sure no bad data gets through. This also allows you to significantly shorten your SQL statement, and allows you to add another value much easier than in the previous example.
public void Save() {
string sql = "INSERT INTO People (First_Name, Last_Name, Age) VALUES (:FirstName, :LastName, :Age);";
using (OracleConnection conn = new OracleConnection("connstring"))
using (OracleCommand comm = new OracleCommand(conn, sql)) {
comm.CommandType = CommandType.Text;
comm.Parameters.Add(":FirstName", OracleType.VarChar, 50).Value = this.FirstName;
comm.Parameters.Add(":LastName", OracleType.VarChar, 50).Value = this.LastName;
comm.Parameters.Add(":Age", OracleType.Int32).Value = this.Age;
comm.ExecuteNonQuery();
}
}This will work for both Oracle and MS SQL, you would just have to change from and Oracle connection and command to a SQL one. Also I think the preferred syntax when using MS SQL would be to use the @ symbol rather than the colon.
Labels: .NET, Back to Basics, SQL
posted by Tom Becker at
|
