Learn Tiny Bit Of C# In 7 Days - Day 1

Introduction
 
As the title specifies “Learn tiny bit of C# in 7 days” I will be writing article for the same, the intended focus is towards the beginners so that they can easily grasp the C# Language concepts and become C# developer after reading the articles. So let’s get started with Day 1. In case you feel I have left the very important topic feel free to comment and any corrective measures and implementation are most welcomed.

welcome

Day1 Contents

  1. Introduction
  2. Agenda
  3. Creating Your First Program
  4. Console Programs
  5. Escape Sequencing
  6. Exceptional Handling
  7. Arrays
  8. For Each Loop

Introduction

C# is object oriented programming language which allows us to build large variety applications. It was developed by Microsoft within .NET framework. C# is one of the many languages that are supported by .NET framework. Its development team is led by Anders Hejlsberg. The Current version is C# 6.0, which was released on July 20, 2015.

What’s the agenda?

As the name specifies learn C#, so we will be going to learn tiny bit C# in 7 days, so that you are foundation is strong and you be prepared to devote next 5 years how to apply it to make something useful or make an impact on the World. For the first day we will cover small but important topics that will keep our foundation of C#. We will move ahead and discuss how to real time applciation using C#.

Creating Your First Program

As you are reading about C# so I hope that you will familiar with Visual Studio IDE. A rich, integrated development environment for creating stunning applications for Windows, Android, and iOS, as well as modern web applications and cloud services. I will be helping you creating your first C# Program step by step.

Step 1: Open Visual Studio.

In case if you don’t have Visual Studio you can download from the following link:

Step 2: Create New Project, click on File, New, then Project.

new peoject

Step 3: Select Visual C#.

You can see the following set of options available with Visual C# using these components we can develop our respective applications.

visual c#

Right now we will select Console Application and name our Project as CSharpStepByStep. We will implement the C # concepts using Console Application because it simplifies the learning process of C#. Once the loading of classes and required component need for visual studio project get loaded we will have our Program.cs file as in the following code snippet:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. namespace CSharpStepByStep  
  7. {  
  8.     class Program  
  9.     {  
  10.         static void Main(string[] args)  
  11.         {  
  12.         }  
  13.     }  
  14. }  
I will be getting rid of little code as it’s our first warm up topic I don’t want you to mess up and confuse. In short I will only keep the code that is necessary.
  1. using System;  
  2. class Program  
  3. {  
  4.     static void Main()  
  5.     {  
  6.     }  
  7. }  
Now you can see I have removed some code that will be discussed in our later section. So now I want to print Welcome to Learn C# Step By Step in console window. By console window I mean to say is Command Prompt. So in order to do that I will just write Console.WriteLine(“message”). Here Console is a class.
  1. using System;  
  2. class Program  
  3. {  
  4.     static void Main()  
  5.     {  
  6.         Console.WriteLine("Learn C# Step by Step");  
  7.     }  
  8. }  
So once I run my application in debug mode the command window just pops up and gets closed, in order to keep the window open we use one more method of Console called Readkey which will not close the console window until and unless the user presses a key or you can run the program using Ctrl+F5 run without debugging.  
  1. using System;  
  2. class Program  
  3. {  
  4.     static void Main()  
  5.     {  
  6.         Console.WriteLine("Learn C# Step by Step");  
  7.         Console.ReadKey();  
  8.     }  
  9. }  
output

Let’s focus little in depth for the above code to understand it better.

Using Sytem:

This line signifies that in our program we are going to make use of System Namespace. So you might be thinking what the hell Namespace is. Namespace is a collection of classes, when we use our Console.WriteLine or Console.ReadLine you may have seen the following

sytem

That specify the Console class is present in the System Namespace, if we remove the Using System Namespace we would get the following compile time error,

error

That means compiler don’t know where do Console exist. We can add the fully conventional keyword System.Console class name before using its function as in the following code snippet,
  1. class Program  
  2. {  
  3.     static void Main()  
  4.     {  
  5.         System.Console.WriteLine("Learn C# Step by Step");  
  6.         System.Console.ReadLine();  
  7.     }  
  8. }  
But doing this we have to use System wherever we want to use the Console Class in order to use System class, so in order to avoid this we use them at top in Using Section.

Every line of code should be inside a Class, we will be discussing about class once we go ahead.
  1. class Program  
  2. {  
  3.     static void Main()  
  4.     {  
  5.         System.Console.WriteLine("Learn C# Step by Step");  
  6.         System.Console.ReadLine();  
  7.     }  
  8. }  
Static Void Main()

Is an entry point function which tells the compiler from where the execution is going to start.

main
Once the program get executed it enter the entry point function and execute the sets of instructions.

Note: When you want to see the flow of program you can insert a breakpoint using F9 and see your program flow line by line.

Console Programs

In this topic we will be enhancing our first program by taking input from the User and displaying the desired results to the User.
As we have learned to write to Console we write Console.WriteLine, so when we want to read the User Input we use Console.ReadLine(); This function reads the next lines of characters from the standard input stream as shown in the above figure. In order to read the User Input we have to read the User Input in a variable *note variable is a location in memory which is used to store data used in Application. Once the value is stored in variable we will display the User entered value concatenated with to learn C #Step by Step as shown below:
  1. using System;  
  2. class Program  
  3. {  
  4.     static void Main()  
  5.     {  
  6.         Console.WriteLine("Learn C# Step by Step"); //printing to the Console  
  7.         Console.WriteLine("Enter your Name"); //printing to the Console  
  8.         string UserName = Console.ReadLine(); //Reading User Input  
  9.         Console.WriteLine("Welcome " + UserName + " to Learn C# Step by Step"); //printing user entered concatenated with other string.  
  10.         Console.ReadLine();  
  11.     }  
  12. }  
Let us go through code,

code

As we can see that Console.WriteLine has been printed to the console window, now yellow shaded lines read the User Input and stores it into variable called UserName and in next line we write the variable value along with string as shown below.

output

C# is a case sensitive language i.e.

The word case sensitive means the text is sensitive to capitalization of letters or words.

Example:

Class and class are two different word because of C of first being Caps. You can see the following figure for more elaboration.

example
Escape Sequencing

Sometimes we need to add Character combinations consisting of a backslash (\) followed by a letter in our programs. Foe example, we want our output to have been like this “Hello Readers” along with double quotes. In order to do that we make use of Escape Sequencing in C#, as defined here the escape sequence character in C# is (\ ). This backslash says to compiler whatever precedes me treat them as a regular character.
  1. using System;  
  2. class Program  
  3. {  
  4.     static void Main()  
  5.     {  
  6.         Console.WriteLine("\"Hello Readers\"");  
  7.         Console.WriteLine("\\heelo reader\\");  
  8.         Console.ReadLine();  
  9.     }  
  10. }  
Output:

output

You can read the chart of Escape sequence from this link.

Exception Handling

Exceptional handling the way of passing control from one part to another i.e. if there is any exception in our program we can catch the same pass the control to another. As you may be aware of Exception Handling I want to sum up the definition of Exception as Exception is the error that occurs when a program is running. So here we will learn how to handle the Exception and how we can respond it to the User in a user friendly manner.

Example: Divide by Zero Exception

exception

So in order to do Exceptional Handling we need two things.

Try, Catch and finally, we can see in above figure from where our Exception was raised or program crashed. Showing the actual unhandled exception will annoy the user as they are cryptic and do not make sense to the end user. We can tell the compiler that I am excepting to get error in this line and in case you get exception can you just throw the Exception into the Catch as in the following code snippet.
  1. using System;  
  2. class Program  
  3. {  
  4.     static void Main()  
  5.     {  
  6.         int a = 10;  
  7.         int b = 0;  
  8.         int result;  
  9.         try  
  10.         {  
  11.             result = a / b;  
  12.             Console.WriteLine("\n Result after division is ", result);  
  13.             Console.ReadLine();  
  14.         }  
  15.         catch (Exception ex)  
  16.         {  
  17.             Console.WriteLine("Divisor should be greater than 0");  
  18.             Console.ReadLine();  
  19.         }  
  20.     }  
  21. }  
Exception is actually a class that derives from System.Exception class. With the help of this we can show the User Friendly message to the Users rather than Compiler message shown by the compiler.

class

An exception Class has several useful properties (we will learn more about properties as we go ahead) that provide valuable information about the Exception. 
  • Message: Describes the current exception details.
  • StackTrace: Provide the call stack to the line number in the method where the exception occurred.

    stacktrace

What if rather than using Exception class we use DivideByZeroException which is a child class of Exception. System.Exception is base class of Exception,

  • DivideByZeroException Inherits from ArithmeticException
  • ArithmeticException Inherits from SystemException
  • SystemException Inherits from Exception

Now using DivideByZeroException:

  1. catch (DivideByZeroException ex)  
  2. {  
  3.     Console.WriteLine("Divisor should be greater then 0");  
  4.     Console.WriteLine(ex.Data.ToString());  
  5.     Console.WriteLine(ex.Message.ToString());  
  6.     Console.WriteLine(ex.StackTrace.ToString());  
  7.     Console.ReadLine();  
  8. }  
output

But this catch block will only handle DivideByZeroException so in order to catch other Exception we can include another catch block and use base exception type as shown below.

Now I am trying to read the content of the file and if any exception occurs while reading the same exception will be handled via Exception class else if while dividing we get divide by zero exception that will be handled by DivideByZero Exception class.
  1. using System;  
  2. using System.IO;  
  3. class Program  
  4. {  
  5.     static void Main()  
  6.     {  
  7.         int a = 10;  
  8.         int b = 0;  
  9.         int result;  
  10.         try  
  11.         {  
  12.             StreamReader obj = new StreamReader(@ "C:\Users\Developer\Documents\Article\.net Framework\Product Ke");  
  13.             Console.WriteLine(obj.ReadToEnd());  
  14.             obj.Close();  
  15.             result = a / b;  
  16.         }  
  17.         catch (DivideByZeroException ex)  
  18.         {  
  19.             Console.WriteLine("Divisor should be greater than 0");  
  20.             Console.ReadLine();  
  21.         }  
  22.         catch (Exception ex)  
  23.         {  
  24.             Console.WriteLine(ex.Message.ToString());  
  25.             Console.ReadLine();  
  26.         }  
  27.     }  
  28. }  
Finally: Here the set of statements are written that you want to execute irrespective of Exception occurs or not. For example, Disposing ADO.NET objects, Close IO objects, etc (*Note we will be discussing these topics ahead). Finally block is not mandatory.

In above code as soon as the Exception occurs the handle is transferred to the Exception class neglecting all other statement after that would result in object occupying the memory. So in order to close the same we will do it in finally block as shown below.
  1. using System;  
  2. using System.IO;  
  3. class Program  
  4. {  
  5.     static void Main()  
  6.     {  
  7.         int a = 10;  
  8.         int b = 0;  
  9.         int result;  
  10.         StreamReader obj = null;  
  11.         try  
  12.         {  
  13.             obj = new StreamReader(@ "C:\Users\Developer\Documents\Article\.net Framework\Product Ke");  
  14.             Console.WriteLine(obj.ReadToEnd());  
  15.             result = a / b;  
  16.         }  
  17.         catch (DivideByZeroException ex)  
  18.         {  
  19.             Console.WriteLine("Divisor should be greater then 0");  
  20.         }  
  21.         catch (Exception ex)  
  22.         {  
  23.             Console.WriteLine(ex.Message.ToString());  
  24.         }  
  25.         finally  
  26.         {  
  27.             if (obj != null)  
  28.             {  
  29.                 obj.Close();  
  30.             }  
  31.             Console.WriteLine("I am finally block");  
  32.             Console.ReadLine();  
  33.         }  
  34.     }  
  35. }  
output

Inner Exceptions

Once while executing our Program we face some exception so we handle the exception in catch block, what if we want to do some operation inside catch block. For example, Writing exception to a text file, etc. In order to do these operations we may face some other Inner Exception inside a catch block so let’s see how we handle the Inner Exceptions. Now as I have mentioned I want to log the Exception to a text file with exception message, trace and data and time.
  1. using System;  
  2. using System.IO;  
  3. class Program  
  4. {  
  5.     static void Main()  
  6.     {  
  7.         int a = 10;  
  8.         int b = 0;  
  9.         int result;  
  10.         try  
  11.         {  
  12.             result = a / b;  
  13.         }  
  14.         catch (Exception ex)  
  15.         {  
  16.             string Filepath = @ "C:\Users\Developer\Documents\Article\.net Framework\Exception.txt";  
  17.             if (File.Exists(Filepath))  
  18.             {  
  19.                 StreamWriter objException = new StreamWriter(Filepath);  
  20.                 objException.Write(DateTime.Now + " " + ex.Message + " " + ex.StackTrace);  
  21.             }  
  22.             else  
  23.             {  
  24.                 throw new FileNotFoundException("File not found " + Filepath, ex.Message);  
  25.             }  
  26.             Console.WriteLine(ex.Message.ToString());  
  27.         }  
  28.     }  
  29. }  
You can see in above code that once the Divide by Zero Exception comes, I am writing the exception to text file as shown below:

exception

What if while writing the Exception I face another exception, so in order to handle that we use Throw Exception as shown above.

output

Arrays

Array is a group of similar data types, Eg. We want to store 10 integers. As this article is focused on C# I will not be going in depth of Arrays. I will help you how to declare and use Arrays in c#.

Syntax of Declaring an Array
  1. int[] intArr = new int[3]; //size to specified  
  2. (name of array)   
array

Example:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. namespace Arrays  
  7. {  
  8.     class Program  
  9.     {  
  10.         static void Main(string[] args)  
  11.         {  
  12.             int[] intArr = new int[10];  
  13.             for (int i = 0; i < 10; i++) //looping threw I and assigning I value to array  
  14.             {  
  15.                 intArr[i] = i;  
  16.             }  
  17.             Console.WriteLine("The Arrays consist of following values");  
  18.             for (int i = 0; i < 10; i++)  
  19.             {  
  20.                 Console.WriteLine(intArr[i]);  
  21.             }  
  22.             Console.ReadLine();  
  23.         }  
  24.     }  
  25. }  
Advantages:
  • Arrays are strongly typed; they don’t allow storing other data type apart from declared data type.
  • 2D arrays are used to represent matrices.

datatype

Figure1: 
Arrays are strongly typed i.e. it can only accept the value of declared datatype.

Disadvantages:

  • Once we declare the array size it cannot be changed.
  • Since the array size is fixed so if we insert less value the memory is wasted and more than System.IndexOutOfRangeException will happen.

Foreach Loop

For each loop is used to iterate through the collection, doesn’t includes initialization, termination and increment / decrement characteristics as in other loops.

Advantages:

  • No need to know the size of the Collection.
  • Loops are easier to write and it is least error prone loop.

Note: Code Snippet for foreach Loop is foreach and then press tab.

Example:

Syntax: foreach(datatype same a collection Datatype name in Collection).

  1. {  
  2.     //statements  
  3. }  
  4. using System;  
  5. using System.Collections.Generic;  
  6. using System.Linq;  
  7. using System.Text;  
  8. using System.Threading.Tasks;  
  9. namespace Arrays  
  10. {  
  11.     class Program  
  12.     {  
  13.         static void Main(string[] args)  
  14.         {  
  15.             int[] intArr = new int[10];  
  16.             //creating a collection of int array  
  17.             for (int i = 0; i < 10; i++)  
  18.             {  
  19.                 intArr[i] = i;  
  20.             }  
  21.             Console.WriteLine("The Array consist of following values");  
  22.             //intArr is a collection   
  23.             foreach(int Value in intArr)  
  24.             {  
  25.                 Console.WriteLine(Value);  
  26.             }  
  27.             Console.ReadLine();  
  28.         }  
  29.     }  
  30. }  
foreach

Figure Demonstrating how For Each loop flows

As we move ahead we learn more benefits of using for each loop.

Conclusion

Here we complete our day 1. In day 2 we will talk about Namespaces, Classes, Inheritance, Access Modifiers, Properties, Interface and Abstract Class. So keep reading, keep learning.

If any confusion you can comment for the same. Any feedback and added information is heartily welcomed. 


Similar Articles