In this chapter, we took a look at some basic C# programming. Here's an overview of the topics we covered: -
C# includes several iterative statements : for , while , do...while , and foreach . The first three loops for , while , do...while are the old standards that appear in many programming languages, but the foreach loop is something new for C++ programmers coming to C#. -
The foreach loop is designed to loop over a collection, which includes arrays. This loop is useful when you want to loop over the elements in a collection, because it loops over them all automatically, without using a loop index. Loop indices, as you use with a for loop, are prone to off-by-one errors (as when you use < instead of <= in the termination expression of the loop), so foreach is a very popular addition to the language. -
The process of creating methods in C# is very similar to creating methods in C++. We took a look at how to create a method, call it, pass data to a method, and return data from a method. We also saw how to write methods that can accept variable numbers of arguments and make use of recursion. -
To avoid the use of pointers, C# has to get a little innovative when it comes to passing value types by reference. Passing variables by reference is good when you want to return multiple values from a method, and C# supports passing value types by reference with the ref and out keywords. You use the ref keyword to pass a value type by reference, and the out keyword when you want to do the same thing but also avoid having to initialize the variable before passing it to a method. -
You can handle runtime exceptions with try-catch-finally statements. You saw how to enclose sensitive code in a try block, catch exceptions in a catch block, filter exceptions, and rethrow them as needed. You even took a look at creating custom exceptions and throwing them. -
C# also has a large number of string methods available, as well as some that support the use of regular expressions. |