Thursday, November 26, 2015

Part 15 -for and foreach loops in c#

Part 13 & 14 - While loop in c#

In this session, we will learn

Part 11 & 12 – switch statement in C#

In this session, we will learn

Part 10 - If statement

In this session, we will learn
1. if statement
2. if else statement
3. Difference between && and &
4. Difference between | | and |

 Difference between && and &:

Both operators are used like:

  • Condition1 && Condition2
  • Condition1 & Condition2
When && is used, then first condition is evaluated and if it comes out to be false then the second condition is not checked because according to the definition of && operator (AND) if both conditions are true only then && returns true else false. So if condition1 evaluates to false then there is no need for checking the condition2 as it always going to return false. It improves the performance of the application as it skips condition2 when condition1 is false else both conditions will be evaluated.

When & is used then both conditions are checked in every case. It first evaluates condition1, irrespective of its result it will always checks the condition2. Then it compares both outputs and if both are true only then it returns true.

I have created a sample code for verifying this concept. For that I have created two methods one returning True and other returning false.
  1. public static bool ReturnsTrue()  
  2.    {  
  3.        return true;  
  4.    }  
  5. public static bool ReturnsFalse()  
  6.    {  
  7.        return false;  
  8.    }  
  9. if (ReturnsFalse() && ReturnsTrue())  
  10.    {  
  11.        Console.WriteLine("Hit");  
  12.    }  
I have called these methods in if statement and since first condition returns False so ReturnsTrue method will never called (check this by putting debugger on both ReturnsTrue and ReturnsFalse method) and if you call ReturnsTrue method first then second method will always be called.

Now check the if condition with & operator
  1. if (ReturnsFalse() & ReturnsTrue())  
  2.    {  
  3.         Console.WriteLine("Hit");              
  4.    }  
It will always check both conditions and both methods will be called. (Check by applying debugger).

So we should always prefer && operator as it improves performance. & operator should only be used when there is a requirement for checking both conditions.
 

Part 9 - Comments

In this session, we will learn
1. Single line comments
2. Multi line comments 
3. Introduction to XML documentation comments
 Comments in C#:
Single line Comments                     -   //
Multi line Comments                   -   /*  */
XML Documentation Comments     -   ///
Comments are used to document what the program does and what specific blocks or lines of code do. C# compiler ignores comments.

To Comment and Uncomment, there are 2 ways
1. Use the designer
2. Keyboard Shortcut: Ctrl+K, Ctrl+C and Ctrl+K, Ctrl+U

Note: Don't try to comment every line of code. Use comments only for blocks or lines of code that are difficult to understand. 

Part 8 - Arrays in C#

In this seesion, we will discuss
1. Arrays
2. Advantages and dis-advantages of arrays
 An array is a collection of similar data types.

using System;
class Program
{
    public static void Main()
    {
        // Initialize and assign values in different lines
        int[] EvenNumbers = new int[3];
        EvenNumbers[0] = 0;
        EvenNumbers[1] = 2;
        EvenNumbers[2] = 4;

        // Initialize and assign values in the same line
        int[] OddNumbers = { 1, 3, 5};

        Console.WriteLine("Printing EVEN Numbers");

        // Retrieve and print even numbers from the array
        for (int i = 0; i < EvenNumbers.Length; i++)
        {
            Console.WriteLine(EvenNumbers[i]);
        }

        Console.WriteLine("Printing ODD Numbers");

        // Retrieve and print odd numbers from the array
        for (int i = 0; i < OddNumbers.Length; i++)
        {
            Console.WriteLine(OddNumbers[i]);
        }
    }
}
 Advantages: Arrays are strongly typed.

Disadvantages: Arrays cannot grow in size once initialized. Have to rely on integral indices to store or retrieve items from the array.

Part 7 - Datatype conversions

In this session, we will learn
1. Implicit conversions
2. Explicit Conversions
3. Difference between Parse() and TryParse()
Implicit & Explicit conversion: 
Implicit conversion is done by the compiler:
       1. When there is no loss of information if the conversion is done
       2. If there is no possibility of throwing exceptions during the conversion 

     Example: Converting an int to a float will not loose any data and no exception will   be thrown, hence an implicit conversion can be done.  

Where as when converting a float to an int, we loose the fractional part and also a possibility of overflow exception. Hence, in this case an explicit conversion is required. For explicit conversion we can use cast operator or the convert class in c#.

Implicit Conversion Example
using System;
class Program
{
    public static void Main()
    {
        int i = 100;

        // float is bigger datatype than int. So, no loss of
        // data and exceptions. Hence implicit conversion
        float f = i;

        Console.WriteLine(f);
    }
}

Explicit Conversion Example
using System;
class Program
{
    public static void Main()
    {
        float f = 100.25F;

        // Cannot implicitly convert float to int.
        // Fractional part will be lost. Float is a
        // bigger datatype than int, so there is
        // also a possiblity of overflow exception
        // int i = f;

        // Use explicit conversion using cast () operator
        int i = (int)f;

        // OR use Convert class
        // int i = Convert.ToInt32(f);

        Console.WriteLine(i);
    }
}

Difference between Parse and TryParse
1. If the number is in a string format you have 2 options - Parse() and TryParse() 
2. Parse() method throws an exception if it cannot parse the value, whereas TryParse() returns a bool indicating whether it succeeded or failed.
3. Use Parse() if you are sure the value will be valid, otherwise use TryParse()

Part 6 - Nullable Types

In this Session , we will learn
1. Nullable types in C#
2. Null Coalescing Operator ??

Types in C#:
         In C# types  are divided into 2 broad categories.
         Value Types  - int, float, double, structs, enums etc
         Reference Types – Interface, Class, delegates, arrays etc

By default value types are non nullable. To make them nullable use ?
int i = 0 (i is non nullable, so "i" cannot be set to null, i = null will generate compiler error)
int? j = 0 (j is nullable int, so j=null is legal)

Nullable types bridge the differences between C# types and Database types

Program without using NULL coalescing operator
using System;
class Program
{
    static void Main()
    {
        int AvailableTickets;
        int? TicketsOnSale = null;

        if (TicketsOnSale == null)
        {
            AvailableTickets = 0;
        }
        else
        {
            AvailableTickets = (int)TicketsOnSale;
        }

        Console.WriteLine("Available Tickets={0}", AvailableTickets);
    }
}

The above program is re-written using NULL coalescing operator
using System;
class Program
{
    static void Main()
    {
        int AvailableTickets;
        int? TicketsOnSale = null;

        //Using null coalesce operator ??
        AvailableTickets = TicketsOnSale ?? 0;

        Console.WriteLine("Available Tickets={0}", AvailableTickets);
    }
} 

Part 5 - Common Operators

In this session We will learn
1.Assignment Operator =
2.Arithmetic Operators like +,-,*,/,% 
3.Comparison Operators like ==, !=,>, >=, <, <= 
4.Conditional Operators like &&, ||
5.Ternary Operator ?:
6.Null Coalescing Operator ??

Program without ternary Operator
using System;
class Program
{
    static void Main()
    {
        int Number = 10;

        bool IsNumber10;

        if (Number == 10)
        {
            IsNumber10 = true;
        }
        else
        {
            IsNumber10 = false;
        }

        Console.WriteLine("i == 10 is {0}", IsNumber10);
    }
}

Same program with ternary Operator
using System;
class Program
{
    static void Main()
    {
        int Number = 10;

        bool IsNumber10 = Number == 10 ? true : false;
        
        Console.WriteLine("i == 10 is {0}", IsNumber10);
    }
}

Part 3&4 - Built-in types & String types

In this session, we will learn
1.Built-in types in C#
i. Boolean type – Only true or false 
ii. Integral Types - sbyte, byte, short, ushort, int, uint, long, ulong,char
iii. Floating Types – float and double
iv. Decimal Types
v. String Type 
2.Escape Sequences in C#
         http://msdn.microsoft.com/en-us/library/h21280bw.aspx
 3.Verbatim Literal
                   Verbatim Literal is a string with an @ symbol prefix, as in @“Hello". 

                   Verbatim literals make escape sequences translate as normal printable   characters to enhance readability. 

           Practical Example:
           Without Verbatim Literal : “C:\\Pragim\\DotNet\\Training\\Csharp” – Less Readable
          With Verbatim Literal : @“C:\Pragim\DotNet\Training\Csharp” – Better Readable

Part 2 - Reading and writing to a console

In this lession, we will discuss
          1. Reading from the console
          2. Writing to the console
          3. Two ways to write to console
                     a) Concatenation
                     b) Place holder syntax – Most preferred

using System;
class Program
{
    static void Main()
    {
        // Prompt the user for his name
        Console.WriteLine("Please enter your name");
        // Read the name from console
        string UserName = Console.ReadLine();
        // Concatenate name with hello word and print
        Console.WriteLine("Hello " + UserName);

        //Placeholder syntax to print name with hello word 
        //Console.WriteLine("Hello {0}", UserName);
    }
}
Note: C# is case sensitive language.

Part 1 - Introduction to C#

In this session
  1. Basic structure of a c# program.
  2. What is a Namespace? 
  3. Purpose of Main Method. 
1. Sample Program:
                           // Namespace Declaration
                              using System;

                               class Pragim
                                    {
                                     public static void Main()
                                          {
                                           // Write to console
                                           Console.WriteLine ("Welcome to
Pavel Resources!"); 
                                           }
                                      }


2.Namespace/Using System declaration:
       The namespace declaration, using System, indicates that you are using the System namespace. If  you omit the using System, declaration, then you have to use the fully qualified name of the Console class. Such as:
                System.Console.WriteLine ("Welcome to Pavel Resources!");

A namespace is used to organize your code and is collection of classes, interfaces, structs, enums and delegates. We will discuss about namespaces in detail in a later session. 

 3.Purpose of Main Method:
        Main method is the entry point into your application 

GridView

gr

Ado.net

Ado

ASP.Net

SQL Server

Sql