Monday, 17 November 2014

C#.NET Tutorial - Day - 9 - The Basics - Function Parameters


FUNCTION PARAMETERS



In the previous post, we had a look at functions. We briefly discussed parameters, but only briefly. While parameters are very simple and straight forward to use, there are tricks which can make them a lot more powerful. 



The first thing that we will take a look at, is the out and ref modifiers. C#, and other languages as well, differ between two parameters: "by value" and "by reference". The default in C# is "by value", which basically means that when you pass on a variable to a function call, you are actually sending a copy of the object, instead of a reference to it. This also means that you can make changes to the parameter from inside the function, without affecting the original object you passed as a parameter. 

With the ref and the out keyword, we can change this behavior, so we pass along a reference to the object instead of its value.


THE REF MODIFIER


Consider the following example:




We create an integer, assign the number 20 to it, and then we use the AddFive() method, which should add 5 to the number. But does it? No. The value we assign to number inside the function, is never carried out of the function, because we have passed a copy of the number value instead of a reference to it. This is simply how C# works, and in a lot of cases, it's the preferred result. However, in this case, we actually wish to modify the number inside our function. Enter the ref keyword:




As you can see, all we've done is adding the ref keyword to the function declaration as well as the call to the function. If you run the program now, you will see that the value of number has now changed, once we return from the function call. 


THE OUT MODIFIER


The out modifier works pretty much like the ref modifier. They both ensure that the parameter is passed by reference instead of by value, but they do come with two important differences: A value passed to a ref modifier has to be initialized before calling the method - this is not true for the out modifier, where you can use un-initialized values. On the other hand, you can't leave a function call with an out parameter, without assigning a value to it. Since you can pass in un-initialized values as an out parameter, you are not able to actually use an out parameter inside a function - you can only assign a new value to it

Whether to use out or ref really depends on the situation, as you will realize once you start using them. Both are typically used to work around the issue of only being able to return one value from a function, with C#. 

Using the out modifier is just like using the ref modifier, as shown above. Simply change the ref keyword to the out keyword.


THE PARAMS MODIFIER



So far, all of our functions have accepted a fixed amount of parameters. However, in some cases, you might need a function which takes an arbitrary number of parameters. This could of course be done by accepting an array or a list as a parameter, like this:




However, calling it would be a bit clumsy. In the shortest form, it would look like this:




It is acceptable, but it can be done even smarter, with the params keyword:




Calling it would then look like this:




Another advantage of using the params approach, is that you are allowed to pass zero parameters to it as well. 

Functions with params can even take other parameters as well, as long as the parameter with the params keyword are the last one. Besides that, only one parameter using the params keyword can be used per function. Here is a last and more complete example:









Sunday, 16 November 2014

C#.NET Tutorial - Day - 8 - The Basics - Functions


FUNCTIONS



A function allows you to encapsulate a piece of code and call it from other parts of your code. You may very soon run into a situation where you need to repeat a piece of code, from multiple places, and this is where functions come in. In C#, they are basically declared like this:






To call a function, you simply write its name, an open parenthesis, then parameters, if any, and then a closing parenthesis, like this:




Here is an example of our DoStuff() function:




The first part, public, is the visibility, and is optional. If you don't define any, then the function will be private. More about that later on

Next is the type to return. It could be any valid type in C#, or as we have done it here, void. A void means that this function returns absolutely nothing. Also, this function takes no parameters, as you can see from the empty set of parentheses, so it's actually just a tad bit boring. Let's change that:





We've changed almost everything. The function now returns an integer, it takes two parameters (both integers), and instead of outputting something, it makes a calculation and then returns the result. This means that we can add two numbers from various places in our code, simply by calling this function, instead of having to write the calculation code each time. While we don't save that much time and effort in this small example, you better believe that you will learn to love functions, the more you use C#. This function is called like this:




As mentioned, this function actually returns something, and it has to, because we told C# that it's supposed to do so. When declaring anything else than void as a return type, we are forcing our self to return something. You can try removing the return line from the example above, and see the compiler complain:

'AddNumbers(int, int)': not all code paths return a value 

The compiler is reminding us that we have a function which doesn't return something, although we promised. And the compiler is pretty clever! Instead of removing the line, try something like this:




You will see the exact same error - but why? Because there is no guarantee that our if statement will evaluate to true and the return line being executed. You can solve this by having a second, default like return statement in the end:




This will fix the problem we created for our self, and it will also show you that we can have more than one return statement in our function. As soon as a return statement is reached, the function is left and no more code in it is executed. In this case, it means that as long as the result is higher than 10, the "return 0" is never reached.



C#.NET Tutorial - Day - 7 - The Basics - Loops


LOOPS

Another essential technique when writing software is looping - the ability to repeat a block of code X times. In C#, they come in 4 different variants, and we will have a look at each one of them.



THE WHILE LOOP

The while loop is probably the most simple one, so we will start with that. The while loop simply executes a block of code as long as the condition you give it is true. A small example, and then some more explanation:




Try running the code. You will get a nice listing of numbers, from 0 to 4. The number is first defined as 0, and each time the code in the loop is executed, it's incremented by one. But why does it only get to 4, when the code says 5? For the condition to return true, the number has to be less than 5,    which in this case means that the code which outputs the number is not reached once the number is equal to 5. This is because the condition of the while loop is evaluated before it enters the code block.

The Do Loop is an ENTRY CONTROL LOOP.





THE DO LOOP

The opposite of while loop is true for the do loop, which works like the while loop in other aspects through. The do loop evaluates the condition after the loop has executed, which makes sure that the code block is always executed at least once.




The output is the same though - once the number is more than 5, the loop is exited.

The Do Loop is an EXIT CONTROL LOOP.





THE FOR LOOP

The for loop is a bit different. It's preferred when you know how many iterations you want, either because you know the exact amount of iterations, or because you have a variable containing the amount. Here is an example on the for loop.





This produces the exact same output, but as you can see, the for loop is a bit more compact. It consists of 3 parts - we initialize a variable for counting, set up a conditional statement to test it, and increment the counter (++ means the same as "variable = variable + 1"). 

The first part, where we define the i variable and set it to 0, is only executed once, before the loop starts. The last 2 parts are executed for each iteration of the loop. Each time, i is compared to our number variable - if i is smaller than number, the loop runs one more time. After that, i is increased by one. 

Try running the program, and afterwards, try changing the number variable to something bigger or smaller than 5. You will see the loop respond to the change.






THE FOREACH LOOP

The last loop we will look at, is the foreach loop. It operates on collections of items, for instance arrays or other built-in list types. In our example we will use one of the simple lists, called an ArrayList. It works much like an array, but don't worry, we will look into it in a later post.





Okay, so we create an instance of an ArrayList, and then we add some string items to it. We use the foreach loop to run through each item, setting the name variable to the item we have reached each time. That way, we have a named variable to output. As you can see, we declare the name variable to be of the string type – you always need to tell the foreach loop which datatype you are expecting to pull out of the collection. In case you have a list of various types, you may use the object class instead of a specific class, to pull out each item as an object. 

When working with collections, you are very likely to be using the foreach loop most of the time, mainly because it’s simpler than any of the other loops for these kind of operations.





C#.NET Tutorial - Day - 6 - The Basics - The Switch Statement


THE SWITCH STATEMENT


The switch statement is like a set of if statements. It's a list of possibilities, with an action for each possibility, and an optional default action, in case nothing else evaluates to true. A simple switch statement looks like this:




The identifier to check is put after the switch keyword, and then there's the list of case statements, where we check the identifier against a given value. You will notice that we have a break statement at the end of each case. C# simply requires that we leave the block before it ends. In case you were writing a function, you could use a return statement instead of the break statement. 

In this case, we use an integer, but it could be a string too, or any other simple type. Also, you can specify the same action for multiple cases. We will do that in the next example too, where we take a piece of input from the user and use it in our switch statement:




In this example, we ask the user a question, and suggest that they enter either yes, no or maybe. We then read the user input, and create a switch statement for it. To help the user, we convert the input to lowercase before we check it against our lowercase strings, so that there is no difference between lowercase and uppercase letters. 

In this example, we ask the user a question, and suggest that they enter either yes, no or maybe. We then read the user input, and create a switch statement for it. To help the user, we convert the input to lowercase before we check it against our lowercase strings, so that there is no difference between lowercase and uppercase letters. 




If none of the case statements has evaluated to true, then the default statement, if any, will be executed. It is optional, as we saw in the previous examples.






C#.NET Tutorial - Day - 5 - The Basics - The IF Statement


THE IF STATEMENT



One of the single most important statements in every programming language is the if statement. Being able to set up conditional blocks of code is a fundamental principal of writing software. In C#, the if statement is very simple to use. If you have already used another programming language, chances are that you can use the if statement of C# straight away. In any case, read on to see how it's used. The if statement needs a boolean result, that is, true or false. In some programming languages, several datatypes can be automatically converted into booleans, but in C#, you have to specifically make the result boolean. For instance, you can't use if(number), but you can compare number to something, to generate a true or false, like we do later on. 


In the previous post we looked at variables, so we will expand on one of the examples to see how conditional logic can be used.




We use 2 if statements to check if the entered number is between 0 and 10, and a companion of the if statement: The else keyword. Its meaning should be obvious to anyone speaking English - it simply offers an alternative to the code being executed if the condition of the if statement is not met. 

As you may have noticed, we don't use the { and } characters to define the conditional blocks of code. The rule is that if a block only contains a single line of code, the block characters are not required. Now, this seems like a lot of lines to simply check a number, doesn't it? It can be done with fewer lines of code, like this:




We put each condition in a set of parentheses, and then we use the || operator, which simply means "or", to check if the number is either more than 10 OR less than 0. Another operator you will be using a lot is the AND operator, which is written like this: &&. Could we have used the AND operator instead? Of course, we simply turn it around a bit, like this:




This introduces a couple of new operators, the "less than or equal too" and the "bigger than or equal too".






Wednesday, 12 November 2014

C#.NET Tutorial - Day - 4 - The Basics - Variables


VARIABLES



A variable can be compared to a storage room, and is essential for the programmer. In C#, a variable is declared like this: 

<data type> <name>; 

An example could look like this: 

string name; 

That's the most basic version. Usually, you wish to assign a visibility to the variable, and perhaps assign a value to it at the same time. It can be done like this: 

<visibility> <data type> <name> = <value>; 

And with an example:




The visibility part is explained elsewhere in this Blog, so let's concentrate on the variable part. We will jump straight to an example of actually using a couple of them:





Okay, a lot of this has already been explained, so we will jump directly to the interesting part. First of all, we declare a couple of variables of the string type. A string simply contains text, as you can see, since we give them a value straight away. Next, we output a line of text to the console, where we use the two variables. The string is made up by using the + characters to "collect" the different parts. 

Next, we urge the user to enter a new first name, and then we use the ReadLine() method to read the user input from the console and into the firstName variable. Once the user presses the Enter key, the new first name is assigned to the variable, and in the next line we output the name presentation again, to show the change. We have just used our first variable and the single most important feature of a variable: The ability to change its value at runtime

Another interesting example is doing math. Here is one, based on a lot of the same code we have just used:




Put this in our Main method, and try it out. The only new "trick" we use here, is the int.Parse() method. It simply reads a string and converts it into an integer. As you can see, this application makes no effort to validate the user input, and if you enter something which is not a number, an exception will be raised. More about those later.



Tuesday, 11 November 2014

C#.NET Tutorial - Day - 3 - The Basics - DATA TYPES



DATA TYPES


Data types are used everywhere in a programming language like C#. Because it's a strongly typed language, you are required to inform the compiler about which data types you wish to use every time you declare a variable, as you will see in the post about variables. In this post we will take a look at some of the most used data types and how they work. 

bool is one of the simplest data types. It can contain only 2 values - false or true. The bool type is important to understand when using logical operators like the if statement. 

int is short for integer, a data type for storing numbers without decimals. When working with numbers, int is the most commonly used data type. Integers have several data types within C#, depending on the size of the number they are supposed to store. 

string is used for storing text, that is, a number of chars. In C#, strings are immutable, which means that strings are never changed after they have been created. When using methods which changes a string, the actual string is not changed - a new string is returned instead. 

char is used for storing a single character

float is one of the data types used to store numbers which may or may not contain decimals.