Learn C# in 7 Days – Day 1

Introduction: As the title specifies “Learn 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.


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
  9. Parallel.ForeachLoop

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 C# in 7 days. For the first day we will cover small but important topics that will keep our foundation of 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. Source : https://www.visualstudio.com/ . I will be helping you creating your first C# Program step by step.

Step1. Open Visual Studio

In case if you don’t have Visual Studio you can download from the below link https://www.visualstudio.com/.

Step2. Create New Project, Click on File=> New=> Project


Step3: Select Visual C#

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


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 shown below:

using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
 using System.Threading.Tasks;
 namespace CSharpStepByStep
 {
 class Program
{
 static void Main(string[] args)
{
}
}
}
 

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.

using System;
class Program
{
static void Main()
{

 }
}

Now you can see I have removed some code that will talk 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. WriteLine is used to write the message or data to the screen or the User. Console.Readline is used to take input from the User, until and unless user presses the input from the keyboard the screen waits for the input.

using System;
class Program
{
static void Main()
{
Console.WriteLine("Learn C# Step by Step");
}
}

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.

using System;
class Program
{
static void Main()
{
Console.WriteLine("Learn C# Step by Step");
Console.ReadKey();
}
}


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

Using System:

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


That specify the Console class is present in the System Namespace, if we remove the Using System Namespace we would get compile 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 shown below


class Program
{
static void Main()
{
System.Console.WriteLine("Learn C# Step by Step");
System.Console.ReadLine();
}
}
 

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 lines of Code should be inside a Class, we will discussing about class once we go ahead.

class Program
{
static void Main()
{
System.Console.WriteLine("Learn C# Step by Step");
System.Console.ReadLine();
}
}
 

Static Void Main()

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


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

*Tip- 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 learnt to write to Console we write Console.WriteLine, so when we want to read the User Input we use Consol.ReadLine(); This function reads the next lines of characters from the standard input stream as shown above in 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:

using System;
 class Program
{
static void Main()
{
Console.WriteLine("Learn C# Step by Step");//printing to the Console
 Console.WriteLine("Enter your Name");//printing to the Console
 string UserName = Console.ReadLine();//Reading User Input
 Console.WriteLine("Welcome "+UserName+ " to Learn C# Step by Step");//printing user entered concatenated with other string.
 Console.ReadLine();
}
}
 

Let go through code


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


  • C# is a case sensitive language i.e.

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

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


//added

Variable

Is the small memory data which are allocated to our program where actual data will be stored.

In below example we are using a String variable to take the input from the User and display the same to the screen.

using System;
 namespace readline
 {
  class Program
{
 static void Main(string[] args)
{
 Console.WriteLine("Enter your Name");
 string userName = Console.ReadLine();
 Console.WriteLine("Your Name is {0}",userName);
 Console.ReadKey();
 }}
}


Console.WriteLine(“Your Name is {0}”,userName);

Here we are concatenate “Your Name is” and userName value

Int

Let take up that we have another requirement of Age, as we all know that age is an integer type. So we have to take integer as a variable. When we try to read the input from the User as shown below the error appears

As the error specifies cannot convert string to a integer, whenever we take input from the user it’s is always treat as a string, so we need to convert it to our required datatype.

using System;
 namespace readline
 {
 class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter your Name");
string userName = Console.ReadLine();
Console.WriteLine("Enter your age");
int userAge =Convert.ToInt16( Console.ReadLine());
Console.WriteLine("Your Name is {0} and your age is {1}",userName,userAge);
Console.ReadKey();
}}}
 

The output of the program if users inputs correct integer value.

Now if I try inserting the non-integer value I will face an exception/error, as shown below “Input string was not in a correct format”. So now to learn about Exceptional Handling we will learn ahead in this article.

//added

Escape Sequencing

Sometimes we need to add Character combinations consisting of a backslash (\) followed by a letter in our programs eg. 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.

using System;
class Program
{
 static void Main()
 {
 Console.WriteLine("\"Hello Readers\"");
 Console.WriteLine("\\heelo reader\\");
 Console.ReadLine();
 }}
 

Output:


You can read the chart of Escape sequence in below mentioned link

https://msdn.microsoft.com/en-us/library/h21280bw.aspx

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 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.

Eg: Divide by Zero 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 shown below.

using System;
 
class Program
  {
 static void Main()
 {
 int a = 10;
 int b = 0;
 int result;
 try {
 result =a/b;
 Console.WriteLine("\n Result after division is ",result);
 Console.ReadLine();
 }
 catch(Exception ex)
 { 
 Console.WriteLine("Divisor should be greater than 0");
 Console.ReadLine();
 }
 }
}
 

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.


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.


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


 catch (DivideByZeroException ex)
 {
 Console.WriteLine("Divisor should be greater then 0");
 Console.WriteLine(ex.Data.ToString());
 Console.WriteLine(ex.Message.ToString());
 Console.WriteLine(ex.StackTrace.ToString());
 Console.ReadLine();
 }


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.

using System;
using System.IO;
 
 class Program
  {
 static void Main()
 {
 int a = 10;
 int b = 0;
 int result;
 try
 {
 StreamReader obj = new StreamReader(@"C:\Users\Developer\Documents\Article\.net Framework\Product Ke");
 Console.WriteLine(obj.ReadToEnd());
 obj.Close();
 result = a / b;
 }
 catch (DivideByZeroException ex)
 {
 Console.WriteLine("Divisor should be greater than 0");
 Console.ReadLine();
 }
 catch (Exception ex)
 {
 Console.WriteLine(ex.Message.ToString());
 Console.ReadLine();
 }
 }
}
 


Finally- here the set of statements are written that you want to execute irrespective of Exception occurs or not. Eg. 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 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.

using System;
using System.IO;
 
 class Program
 {
 static void Main()
 {
 int a = 10;
 int b = 0;
 int result;
 StreamReader obj = null;
 try
{
  obj = new StreamReader(@"C:\Users\Developer\Documents\Article\.net Framework\Product Ke");
 Console.WriteLine(obj.ReadToEnd());
 result = a / b;
 }
 catch (DivideByZeroException ex)
 {
 Console.WriteLine("Divisor should be greater then 0");
 }
 catch (Exception ex)
 {
 Console.WriteLine(ex.Message.ToString());
 }
 finally
 {
 if(obj!=null)
 {
 obj.Close();
 }
 Console.WriteLine("I am finally block");
 Console.ReadLine();
 }
 }
}
 


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 eg. 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.

using System;
using System.IO;
 
class Program
 {
 static void Main()
 {
 int a = 10;
int b = 0;
 int result;
 try
 {
 result = a / b;
 }
 catch (Exception ex)
 {
 string Filepath = @"C:\Users\Developer\Documents\Article\.net Framework\Exception.txt";
if (File.Exists(Filepath))
 {
  StreamWriter objException = new StreamWriter(Filepath);
 objException.Write(DateTime.Now+" "+ex.Message+" "+ex.StackTrace);
 }
 else
 {
 throw
 new
 FileNotFoundException("File not found "+ Filepath,ex.Message);
 }
 Console.WriteLine(ex.Message.ToString());
 }
 }
}
 

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


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


Arrays

An array is a group of similar data types, Eg. I 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
 int[] intArr = new
 int[3]; //size to specified
 (name of array)
 


Eg:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 namespace Arrays
 {
 class Program
 {
 static void Main(string[] args)
 {
 int[] intArr = new int[10];
 for (int i = 0; i < 10; i++) //looping threw I and assigning I value to array
 {
 intArr[i] = i;
 }
 Console.WriteLine("The Arrays consist of following values");
 for(int i=0;i<10;i++)
 {
 Console.WriteLine(intArr[i]);
 }
 Console.ReadLine();
 }
 }
}
 

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.


Fig 1: 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 insert less value the memory is wasted and more than System.IndexOutOfRangeException will happen.

Foreach Loop

For each loop is used to iterate threw 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, it least error prone loop.

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

Ex:

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

{

//statements

}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Arrays
{
 class Program
 {
 static void Main(string[] args)
 {
 int[] intArr = new int[10];
 //creating a collection of int array
 for (int i = 0; i < 10; i++)
 {
 intArr[i] = i;
 }
 Console.WriteLine("The Array consist of following values");
 //intArr is a collection 
foreach (int Value in intArr)
  {
Console.WriteLine(Value);
 }
  Console.ReadLine();
 }
}
 }
 


Fig: Demonstrating how Actually For Each Loop Flows

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

Parallel ForeachLoop

In .net Microsoft® .NET Framework 4 Microsoft provide Parallel Computing features which specifies new programming working model for writing multi-threaded and asynchronous code . I won’t be going in depth of that and will focus on Parallel ForeachLoop given in Parallel Computing.

As we have learn above about Foreach loop we also have Parallel foreach loop. In sequential foreach loop, the loop is run from a single thread, while in Parallel Foreach loop it uses multiple threads. The implementation of Parallel Foreach loop should be done when we have our independent set of statements i.e. not depending upon each other. The parallel loop runs faster when the computer has available cores.

Conclusion

If you want to watch and learn C# you can  start with C# the below video Learn C# in 60 days.

Here we have successfully completed 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 there is any confusion you can comment us for the same. Any feedbacks and added information is heartily welcomed.

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.