Thursday, 4 December 2014

C#.NET Tutorial - Day - 24 - Debugging - The tool windows


THE TOOL WINDOWS



When debugging in Visual Studio or one of the Express versions, the tool windows in the bottom of the screen will change and new windows will be revealed (unless you have turned them off). The windows are called something along the lines of "Locals", "Watch", "Call stack" and "Immediate window" and they are all related to the debugging experience. In this chapter we will look into each of them and show you what they can do for you.


Locals

This window is the most simple of them all. When a breakpoint is hit, all local variables will be listed here, allowing you to get a quick overview of their name, type and value. You can even right-click in the grid and select "Edit value", to give a variable a new value. This allows you to test your code under other conditions than the current ones.


Watch

The Watch window is a bit like the Locals window, only here you get to decide which variables are tracked, local or global. You can add variables to watch over by dragging them from the code window, from the Locals window or by writing its name on the last, empty line. Your variables will stay in the Watch window until you remove it again, but will only be updated when you are debugging within the current scope. For instance, a variable in function A will not be updated when you are stepping through function B. Just like with the Locals window, you can right-click a watched variable and select "Edit value" to change the current value of the variable.


Call Stack

The Call Stack window will show you the current hierarchy of called functions. For instance, if function A calls function B which calls function C which then calls function D, the Call Stack window will show it, and you will be able to jump to each of the function declarations. You can also see which parameters were passed to each function. In the simple examples we have worked with so far, this might seem pointless, since keeping track of which function calls which function is trivial, but as soon as your code reaches a higher level of complexity and you have function in classes calling function in other classes, the Call Stack can be a real life saver.


Immediate window

The Immediate window is probably the most useful of them all. It allows you to execute custom lines of code in the current context of the debugger. This allows you to check variables, alter their values or just simply test a line of code. You simply type it into the window, hit Enter and the line will be executed. Type a variable name, and its value will be printed. Set a variable value by writing a = 5. The result, if any, will be printed and any changes you make, will be reflected when you continue the execution of the code. The Immediate window is like a C# terminal, where you can enter code and see the results immediately - once you get used to it, you might become addicted. I know I am.



Wednesday, 3 December 2014

C#.NET Tutorial - Day - 23 - Debugging - Stepping through the code


STEPPING THROUGH THE CODE



In this post, we will look into stepping through your code, which is another very essential part of debugging. For the purpose, I have written this simple application: 




It simply manipulates the variable "a" a couple of times and the outputs the final result. Try placing a breakpoint, as described in the previous post, on the very first line where a is used (and declared). Now run the application. The execution is stopped and you can hover your mouse over the a, to ensure that what we learned in the previous post is in fact true: The variable only contains the default value, because the code that assigns the value (in this case 5), has not been executed yet, but let's change that. From the Debug menu, select the "Step over" option, or even better, use the keyboard shortcut F10. The execution will now proceed to the next relevant line and if you hover your mouse over the a variable, you will now see that it has a value. Try again, and you will see the value change according to the lines being executed one by one, until you have reached the end. 

Okay, so that was pretty basic, but also very useful, as you will realise once you start writing more complicated code. In this example, the flow of the code was very simple, since we stayed within a single function, but what if your code starts spreading over multiple classes and/or functions? Try this example: 





Place a breakpoint on the first line of the Main method and run the application. Now use the "Step over" function to step through each line. As you will see, it moves over the function call without any notice - that's simply how debugging works. Now, try again, from the start, and once you have stepped to the line with the MakeComplicatedCalculation() call, select Debug -> Step into, or use the keyboard shortcut F11. The debugger now steps into the first possible function call, allowing you to step through that function as well. As you can probably imagine, this allows you to step through a complicated block of code, while only entering the function calls that interests you. 

If you step into a function and then realise that you would rather return to the previous context, you use the very logically named option from the Debug menu called "Step out" (keyboard shortcut is Shift+F11). This will return you to your previous context, which obviously means that you can step into as many function calls as you want to, and then find your way back by using the step out option.

Tuesday, 2 December 2014

C#.NET Tutorial - Day - 22 - Debugging - Breakpoints


BREAKPOINTS



The very first thing about debugging that you need to know, is the breakpoint. It actually does exactly what the name implies - it marks a point in your code where the execution will take a break (and no, it won't actually break your code, don't worry). Placing a breakpoint in Visual Studio or one of the Express versions, is as simple as left-clicking in the gutter, which is the grey are to the left of your code. Once you click it, you will get a shiny, red circle as a reward - this circle marks where the debugger will halt when you execute your application. You better have a look for your self, and to see the effect, we will use the following piece of code: 




Now, can you predict the result just from looking at the code? Probably, and if not, you could just get out the old calculator and do the math, but that's not really the point. Just imagine the amount of code being much bigger, and let's debug the thing! Place a breakpoint by clicking in the left gutter - your IDE should now look something like this: 




Okay, you're ready to start your first debugging session. As soon as you have placed the breakpoint, you can just run your application like you normally would - from the menu, the toolbar or by pressing F5. What happens now is that the application is executed just like normal, but as soon as a line with a breakpoint is reached, the execution is stopped right before that line would be executed. In this case, it means that the variables a, b and c will have a value, but d will only have it's default value (which is 0 for an integer), since it won't be set before the line with the breakpoint has been evaluated. Now, here comes the cool part - try hovering your mouse over the different variables - the IDE will tell you what they contain. As mentioned, the d variable will have it's default value, but let's change that, by moving forward in the execution. In the next post, I will show you how to navigate around your code, while it's being executed.

Monday, 1 December 2014

C#.NET Tutorial - Day - 21- Debugging - Introduction to Debugging


INTRODUCTION TO DEBUGGING



When you get past the most basic "Hello world!" examples, your code will reach a level of complexity where you can't necessarily figure out what's going on just by running it. What you need, is some black magic, which allows you to open the virtual hood of your application while it's running and see what's going on. Debugging is that magical tool, and as soon as you learn the most basic steps of it, you will wonder how you ever lived without it. It's a tool that every good programmer should understand, simply because it's almost impossible to fix bugs in complex code without it. 

The most basic type of debugging, which is still being used by even advanced programmers, is sometimes called "print debugging" - a simple procedure, where you make your application print a piece of text or a number somewhere, allowing you to see which part of your code has been reached and what your variables contain. With C#, you can use the Console.Write() method, to output the contents of a variable or a simple status message, which will be printed to the console. That can be enough for some situations, but if you're using a nice IDE like Visual Studio or one of the Express versions, you have much stronger tools to your disposal, and they are every bit as easy to use, once you learn the most basic principles. In the next couple of posts, we will guide you through the debugging possibilities of your IDE and after that, you will be a much stronger programmer.



Sunday, 30 November 2014

C#.NET Tutorial - Day - 20 - Classes - Interfaces


INTERFACES



In previous posts, we had a look at abstract classes. Interfaces are much like abstract classes and they share the fact that no instances of them can be created. However, interfaces are even more conceptual than abstract classes, since no method bodies are allowed at all. So an interface is kind of like an abstract class with nothing but abstract methods, and since there are no methods with actual code, there is no need for any fields. Properties are allowed though, as well as indexers and events. You can consider an interface as a contract - a class that implements it is required to implement all of the methods and properties. However, the most important difference is that while C# doesn't allow multiple inheritance, where classes inherit more than a single base class, it does in fact allow for implementation of multiple interfaces! 

So, how does all of this look in code? Here's a pretty complete example. Have a look, perhaps try it out on your own, and then read on for the full explanation: 



 


Let's start in the middle, where we declare the interface. As you can see, the only difference from a class declaration, is the keyword used - interface instead of class. Also, the name of the interface is prefixed with an I for Interface - this is simply a coding standard, and not a requirement. You can call your interfaces whatever you want, but since they are used like classes so much that you might have a hard time telling the difference in some parts of your code, the I prefix makes pretty good sense. 

Then we declare the Describe method, and afterwards, the Name property, which has both a get and a set keyword, making this a read and writeable property. You will also notice the lack of access modifiers (public, private, protected etc.), and that's because they are not allowed in an interface - they are all public by default. 

Next up is our Dog class. Notice how it looks just like inheriting from another class, with the colon between the class name and the class/interface being subclassed/implemented. However, in this case, two interfaces are implemented for the same class, simply separated by a comma. You can implement as many interfaces as you want to, but in this case we only implement two - our own IAnimal interface, and the .NET IComparable interface, which is a shared interface for classes that can be sorted. Now as you can see, we have implemented both the method and the property from the IAnimal interface, as well as a CompareTo method from the IComparable interface. 

Now you might be thinking: If we have to do all the work our self, by implementing the entire methods and properties, why even bother? And a very good example of why it's worth your time, is given in the top of our example. Here, we add a bunch of Dog objects to a list, and then we sort the list. And how does the list know how to sort dogs? Because our Dog class has a CompareTo method that can tell how to compare two dogs. And how does the list know that our Dog object can do just that, and which method to call to get the dogs compared? Because we told it so, by implementing an interface that promises a CompareTo method! This is the real beauty of interfaces.

Saturday, 29 November 2014

C#.NET Tutorial - Day - 19 - Classes - More Abstract Classes


MORE ABSTRACT CLASSES



In the previous post, we had a look at abstract classes. In this post, we will expand the examples a bit, and throw in some abstract methods as well. Abstract methods are only allowed within abstract classes. Their definition will look like a regular method, but they have no code inside them: 




So, why would you want to define an empty method that does nothing? Because an abstract method is an obligation to implent that very method in all subclasses. In fact, it's checked at compile time, to ensure that your subclasses has this method defined. Once again, this is a great way to create a base class for something, while still maintaining a certain amount of control of what the subclasses should be able to do. With this in mind, you can always treat a subclass as its baseclass, whenever you need to use methods defined as abstract methods on the baseclass. For instance, consider the following example: 



































As you can see, we create an ArrayList to contain our animals. We then instantiate a new dog and a new cat and add them to the list. They are instantiated as a Dog and a Cat respectively, but they are also of the type FourLeggedAnimal, and since the compiler knows that subclasses of that class contains the Describe() method, you are actually allowed to call that method, without knowing the exact type of animal. So by typecasting to the FourLeggedAnimal, which is what we do in the foreach loop, we get access to members of the subclasses. This can be very useful in lots of scenarios.



Friday, 28 November 2014

C#.NET Tutorial - Day - 18 - Classes - Abstract Classes


ABSTRACT CLASSES



Abstract classes, marked by the keyword abstract in the class definition, are typically used to define a base class in the hierarchy. What's special about them, is that you can't create an instance of them - if you try, you will get a compile error. Instead, you have to subclass them, as taught in the post on inheritance, and create an instance of your subclass. So when do you need an abstract class? It really depends on what you do. 

To be honest, you can go a long way without needing an abstract class, but they are great for specific things, like frameworks, which is why you will find quite a bit of abstract classes within the .NET framework it self. A good rule of thumb is that the name actually makes really good sense - abstract classes are very often, if not always, used to describe something abstract, something that is more of a concept than a real thing. 

In this example, we will create a base class for four legged animals and then create a Dog class, which inherits from it, like this:





If you compare it with the examples in the post about inheritance, you won't see a big difference. In fact, the abstract keyword in front of the FourLeggedAnimal definition is the biggest difference. As you can see, we create a new instance of the Dog class and then call the inherited Describe() method from the FourLeggedAnimal class. Now try creating an instance of the FourLeggedAnimal class instead:





You will get this fine compiler error: 

Cannot create an instance of the abstract class or interface 'AbstractClasses.FourLeggedAnimal' 

Now, as you can see, we just inherited the Describe() method, but it isn't very useful in it's current form, for our Dog class. Let's override it:





In this case, we do a complete override, but in some cases, you might want to use the behavior from the base class in addition to new functionality. This can be done by using the base keyword, which refers to the class we inherit from:





Now obviously, you can create other subclasses of the FourLeggedAnimal class - perhaps a cat or a lion? In the next post, we will do a more advanced example and introduce abstract methods as well. Read on.