Book Image

Hands-On Object-Oriented Programming with C#

By : Raihan Taher
Book Image

Hands-On Object-Oriented Programming with C#

By: Raihan Taher

Overview of this book

Object-oriented programming (OOP) is a programming paradigm organized around objects rather than actions, and data rather than logic. With the latest release of C#, you can look forward to new additions that improve object-oriented programming. This book will get you up to speed with OOP in C# in an engaging and interactive way. The book starts off by introducing you to C# language essentials and explaining OOP concepts through simple programs. You will then go on to learn how to use classes, interfacesm and properties to write pure OOP code in your applications. You will broaden your understanding of OOP further as you delve into some of the advanced features of the language, such as using events, delegates, and generics. Next, you will learn the secrets of writing good code by following design patterns and design principles. You'll also understand problem statements with their solutions and learn how to work with databases with the help of ADO.NET. Further on, you'll discover a chapter dedicated to the Git version control system. As you approach the conclusion, you'll be able to work through OOP-specific interview questions and understand how to tackle them. By the end of this book, you will have a good understanding of OOP with C# and be able to take your skills to the next level.
Table of Contents (16 chapters)

Fundamentals and syntax of C# language

Being a high-level language, C# is adorned with a lot of newer and updated syntax, which helps the programmer to write code efficiently. As we mentioned earlier, the type system that's supported by the language is divided into two types:

  • Value types
  • Reference types

The value types are generally primitive types that are stored in the stack during local execution for faster allocation and deallocation of memory. The value types are mostly used during the development of code and, consequently, this forms the major spectrum of the code altogether.

Data types

The basic data types of C# are divided into the following categories:

  • Boolean type: bool
  • Character type: char
  • Integer types: sbyte, byte, short, ushort, int, uint, long, and ulong
  • Floating-point types: float and double
  • Decimal precision: decimal
  • String: string
  • Object type: object

These are primitive data types. These data types are embedded in the C# programming language.

Nullable types

The primitive types or value types are not nullable in C#. Consequently, there is always a requirement for the developer to make the type nullable, as a developer might need to identify whether the value is provided explicitly or not. The newest version of .NET provides nullable types:

Nullable<int> a = null;
int? b = a; //same as above

Both lines in the preceding example define the nullable variable, while the second line is just a shortcut of the first declaration. When the value is null, the HasValue property will return false. This will ensure that you can detect whether the variable is explicitly specified as a value or not.

Literals

Literals are also an important part of any program. C# language gives the developer different kinds of options that allow the programmer to specify literals in code. Let's take a look at the different types of literals that are supported.

Boolean

Boolean literals are defined in the form of true or false. No other values except true and false can be assigned in the Boolean type:

bool result = true;

The default value of a Boolean type is false.

Integer

An integer is a number that can have a plus (+) or minus (-) sign as a prefix, but this is optional. If no sign is given, it is considered as positive. You can define numeric literals in int, long, or hexadecimal form:

int numberInDec = -16;
int numberInHex = -0x10;
long numberinLong = 200L;

You can see that the first literal, -16, is a literal that's been specified in an integer variable, while the same value is assigned to an integer using a hexadecimal literal. The long variable is assigned a value with an L suffix.

Real

Real values are sequences of digits with a positive or negative sign, like integers. This also makes it possible to specify fraction values:

float realNumber = 12.5f;
realNumber = 1.25e+1f;
double realdNumber = 12.5;

As you can see, the literal in the last line, 12.5, is double by default, hence it needed to be assigned to a double variable, while the first two lines specify the literal in float types. You can also specify d or D as a suffix to define a double, like f or F for float and m for decimal.

Character

Character literals need to be kept inside a single quote. The value of the literal can be as follows:

  • A character, for example, c
  • A character code, for example, \u0063
  • An escape character, for example, \\ (the forward slash is an escape character)

String

A string is a sequence of characters. In C#, a string is represented by double quotation marks. There are different ways a string can be created in C#. Let's look at the different ways of creating a string in C#:

string s = "hello world";
string s1 = "hello \n\r world"; //prints the string with escape sequence
string s2 = @"hello \n\r world"; //prints the string without escape sequence
string s3 = $"S1 : {s1}, S2: {s2}"; // Replaces the {s1} and {s2} with values

The @ character can be placed as a prefix before a string to take the string as it is, without worrying about any escape characters. It is called a verbatim string. The $ character is used as a prefix for string interpolation. In case your string literal is preceded with the $ sign, the variables are automatically replaced with values if they're placed within { } brackets.

Programming syntax – conditions

Conditions are one of the most common building blocks of any program. A program cannot have single dimensions; comparison, jumps, and breaks are the most common forms of practice in C#. There are three types of conditions available:

  • if...else
  • switch-case
  • goto (lumps without condition)

If-else construct

The most commonly used conditional statement is the if-else construct. The building block of the if-else structure contains an if keyword, followed by a Boolean expression and a set of curly brackets to specify the steps to execute. Optionally, there could be an else keyword, followed by curly brackets for the code to execute when the if block is false:

int a = 5;
if (a == 5)
{
// As a is 5, do something
}
else
{
// As a is not 5, do something
}

The if-else construct can also have an else-if statement to specify multiple criteria for execution.

Switch-case construct

Switch-case, on the other hand, is almost similar to the if statement; in this statement, the cases will determine the execution step. In the case of switch, this always falls in a discrete set of values, and hence, those values can be set up:

int a = 5;
switch (a)
{
case 4:
// Do something;
break;
case 5:
// Do something;
break;
default:
// Do something;
break;
}

The switch case automatically picks the correct case statement, depending on the value, and executes the steps defined inside the block. A case need to be concluded with a break statement.

goto statements

Even though they are less popular and it is not advisable to use them, goto statements are used for unconditional jumps in the language and they are widely used by the language itself. As a developer, you can use a goto statement to jump to any location of your program with the context you have:

... code block
goto lbl1;
...
...
lbl1: expression body

The goto statement directly jumps to the location specified without any condition or criteria.

Programming syntax – loops

For a repetitive task during execution, loops play a vital role. Loops allow the programmer to define a criteria in which the loop will end or until the loop should execute, depending on the type of loop. There are four types of loops:

  • While
  • Do-while
  • For
  • Foreach

The while construct

A loop is used in the programming world to make a sequence of execution steps repeat itself until the condition is met. The while loop is one of the building blocks of the C# programming architecture and is used to loop through the body mentioned in curly brackets until the condition mentioned in the while criteria is true:

while (condition)
{
loop body;
}

The condition mentioned in the loop should evaluate to true to execute the loop for the next iteration.

The do-while construct

The do...while construct checks the condition after executing the step once. Even though the do...while loop is similar to the while loop, the only difference between a do...while loop and a while loop is that a do...while loop will execute the body at least once, even if the criteria is false:

do
{
loop body;
}
while (condition);

The for construct

The most popular loop in the language is the for loop, which handles complications by maintaining the number of executions of the loop efficiently within the block itself:

for (initialization; condition; update)
{
/* loop body */
}

The for loop has a few sections in the criteria. Each of these is separated by a semicolon (;). The first portion defines the index variable, which is executed once before executing the loop. The second portion is the condition that is executed in every iteration of the for loop. If the condition becomes false, the for loop doesn't continue its execution and stops. The third portion is also executed after every execution of the loop body and it manipulates the variable that was used in the for loop initialization and condition.

The foreach construct

The foreach loops are new to the language and are used to iterate over a sequence of objects. Even though this is purely syntactic sugar in the language, the foreach loop is widely used when dealing with collections. The foreach loop inherently uses an IEnumerable<object> interface and should only be used for objects implementing this:

foreach (type variable in collection)
{
//statements;
}

Contextual – break and continue statements

If you are working with loops, it is very important to understand two more contextual keywords that make it possible to interact with loops.

Break

This allows the developer to break the loop and take the context out of the loop, even though the criteria is still valid. The programming contextual keyword, break, is used as a bypass to break the loop in which it is getting executed. The break statement is valid inside loops and switch statements.

Continue

This is used to invoke the next iteration. The contextual keyword allows the developer to continue to the next step without executing any further code in the block.

Now, let's look at how we can use both of these contextual statements in our program:

var x = 0;
while(x<=10)
{
x++;
if(x == 2)continue;
Console.WriteLine(x);
if(x == 5) break;
Console.WriteLine("End of loop body");
}
Console.WriteLine($"End of loop, X : {x}");

The preceding code will skip execution of the body for the iteration value, 2, because of the continue statement. The loop will execute until the value of x is 5 because of the break statement.