All Type Coding

Search Here

foreach loop in C#?

foreach loop
foreach loop is a different kind of looping constructs in C# programming that doesn’t includes initialization, termination and increment/decrement characteristics. It uses collection to take value one by one and then processes them or A program iterates over a collection. The index of each element is not needed. Only the elements are needed. With foreach we access just the elements
syntax:
 foreach (string name in arr)
 {
 }

For Example

using System;

namespace foreach_loop
{
  class Program
   {
     static void Main(string[] args)
      {
        string[] arr = new string[5]; // declaring array

        //Storing value in array element
        arr[0] = "A";
        arr[1] = "B";
        arr[2] = "C";
        arr[3] = "D";
        arr[4] = "E";

        //retrieving value using foreach loop
        foreach (string name in arr)
         {
           Console.WriteLine("Hello " + name);
         }
        Console.ReadLine();
      }
   }
}


Output is:



For Loop in c#

For Loop 
for loop is another powerful loop construct in C#. It is powerful and easy to use. for loop includes all three characteristics as initialization, termination and increment/decrement in a single line.

for (initialization; termination; increment/decrement) ;

There are many situation when you need to execute a block of statements several number of times in your applications. The for loop in C# is useful for iterating over arrays and for sequential processing. This kind of for loop is useful for iterating over arrays and for other applications in which you know in advance how many times you want the loop to iterate. That is the statements within the code block of a for loop will execute a series of statements as long as a specific condition remains true.
Every for loops defines initializer, condition, and iterator sections.
Syntax:

for(initialization; condition; step) code statement


Initialization : Initialize the value of variable. 
condition : Evaluate the condition 
step  : Step taken for each execution of loop body 


The for loop initialize the value before the first step. Then checking the condition against the current value of variable and execute the loop statement and then perform the step taken for each execution of loop body.

  for (i = 1; i <= 10; i++)
            {
                result = num * i;
                Console.WriteLine("{0} x {1} = {2}", num, i, result);
            }

The initializer declares and initializes a local loop variable, i, that maintains a 10 of the iterations of the loop. The loop will execute 10 times because we set the condition i is less than or equal to count.
  for (int i = 1; i < = 10; i++)

  initialization : int i = 1
  Initialize the variable i as 1, that is when the loop starts the value of i is set as 1
  condition  : i < = 10
  Set the condition i < =10, that is the loop will execute up to

when the value of i < = 10 (Ten times)


  step   : i++

Set the step for each execution of loop block as i++ ( i = i +1)

The output of the code as follows :



Infinite Loop
All of the expressions of the for loop statements are optional. A loop becomes infinite loop if a condition never becomes false. You can make an endless loop by leaving the conditional expression empty. The following statement is used to write an infinite loop.

  for (; ; )   {     // statements   } 


Here the loop will execute infinite times because there is no initialization , condition and steps.
Break and Continue
We can control for loop iteration with the break and continue statements. break terminates iteration and continue skips to the next iteration cycle. The following program shows a simple example to illustrate break and continue statement.


using System;

    class Program
    {
        static void Main(string[] args)
        {
            int num, i, result;
            Console.Write("Enter a number\t");
            num = Convert.ToInt32(Console.ReadLine());

            for (i = 1; i <= 10; i++)
            {
                result = num * i;
                Console.WriteLine("{0} x {1} = {2}", num, i, result);
            }
            Console.ReadLine();
        }
    }
Output:










Nested Loop
C# allows to use one loop inside another loop. Following section shows few examples to illustrate the concept.
Syntax:
for ( init; condition; increment )
{
   for ( init; condition; increment )
   {
      statement(s);
   }
   statement(s);
}

A sample prime number program for nested for loop 
using System;
    class Program
    {
        static void Main(string[] args)
        {
            
            int i, j;
            for (i = 2; i < 50; i++)
            {
                for (j = 2; j <= (i / j); j++)
                    if ((i % j) == 0) break; 
                if (j > (i / j))
                    Console.WriteLine("{0} is prime", i);
            }
            Console.ReadLine();
        }
}
Output will be:











IF Statement in c#

IF Statement 
The conditional statement if.. else in C# is using for check the conditions 
An if statement can be followed by an optional else statement, which executes when the boolean expression is false.
The conditional statement examining the data using comparison operators as well as logical operators. The else statement is optional , so we can use the statement in two ways ;
1- if (condition)
{
  statement;
}
   
2- if (condition)
{
 statement;
}  
else
{
 statement;
}

If the condition is true then the control goes to the body of if block , that is the program will execute the code inside if block.If the condition is false then the control goes to next level , if you provide else block the program will execute the code block of else statement, otherwise the control goes to next line of code.
If you want to check more than one conditions at the same time , you can use else if statement .

  if (condition)
{
  statement;
}  
else if(condition)
{
 statement;
}
else if(condition)
{
 statement;
}

Here we will see how to use if statement let's say we'll compare three number to each other and got highest  number out of three


using System;

class abc
{
    int a, b, c, d, e, f, g;
    public void grt()
    {
        Console.WriteLine("Enter first no that is a");
        a = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("Enter second no that is b");
        b = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("Enter third no that is c");
        c = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("Enter third no that is d");
        d = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("Enter third no that is e");
        e = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("Enter third no that is f");
        f = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("Enter third no that is g");
        g = Convert.ToInt32(Console.ReadLine());

        if ((a > b) && (a > c) && (a > d) && (a > e) && (a > f) && (a > g))
        {
            Console.WriteLine("a is greater");
        }
        else if ((b > a) && (b > c) && (b > d) && (b > e) && (b > f) && (b > g))
        {
            Console.WriteLine("b is greater");
        }
        else if ((c > a) && (c > b) && (c > d) && (c > e) && (c > f) && (c > g))
        {
            Console.WriteLine("c is greater");
        }
        else if ((d > a) && (d > b) && (d > c) && (d > e) && (d > f) && (d > g))
        {
            Console.WriteLine("d is greater");
        }
        else if ((e > a) && (e > b) && (e > c) && (e > d) && (d > f) && (d > g))
        {
            Console.WriteLine("e is greater");
        }
        else if ((f > a) && (f > b) && (f > c) && (f > d) && (f > e) && (f > g))
        {
            Console.WriteLine("f is greater");
        }
        else
        {
            Console.WriteLine("g is greater");
        }
        Console.ReadKey();
    }
}
class grt2
{
    public static void Main(string[] args)
    {
        abc a = new abc();
        a.grt();
    }
}
Output



Comments in c#

Comments 
Comments can be used to document what the program does and what specific blocks or lines of code do. Since the C# compiler ignores comments, you can include them anywhere in a program without affecting your code.
The are following  types of comments in C#
1. Single line comments
2. Multi line comments 
3. Introduction to XML documentation comments  

Single line Comments                       -   //
Multi line Comments                     -   /*  */
XML Documentation 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

C# Access Specifiers,C# Access Modifiers

Why to use access modifiers?
Access Modifiers (Access Specifiers) are keywords used to specify the declared accessibility of a member or a type. Access modifiers are an integral part of object-oriented programming. They support the concept of encapsulation, which promotes the idea of hiding functionality. Access modifiers allow you to define who does or doesn't have access to certain features.
C# provide five access specifiers , they are as follows 
1-public,
2-private ,
3-protected ,
4-internal 
5-and protected internal 
Here we will learn above access specifiers
1-public
It can be access from anywhere, that means there is no restriction on accessibility. The scope of the accessibility is inside class as well as outside. The type or member can be accessed by any other code in the same assembly or another assembly that references it.
Example: In the following example num1 is direct access.  

 using System;
   class Program
    {
        class AccessMod
        {
            public int num1;
        }

        static void Main(string[] args)
        {

            AccessMod ob1 = new AccessMod();

            //Direct access to public members

            ob1.num1 = 100;
            Console.WriteLine("Number one value in main {0}", ob1.num1);

            Console.ReadLine();

        }

    }

2-private 
Access is limited to within the class definition.struct in which they are declared. The private members cannot be accessed outside the class and it is the least permissive access level.

 Example: In the following example num2 is not accessible outside the class. 

using System;
    class Program
    {

        class AccessMod
        {

            public int number1;

            int number2;

        }

        static void Main(string[] args)
        {
            AccessMod ob1 = new AccessMod();
            //Direct access to public members

            ob1.a = 100;

            //Access to private member is not permitted
            ob1.number = 30;

            Console.WriteLine("Number one value in main {0}", ob1.a);

            Console.ReadLine();

        }

    }


 


























The above program will give compilation error, as access to private is not permissible. In the below figure you can see the private member number2 is not available. 
3-protected
Access is limited to within the class definition and any class that inherits from the class.
The type or member can be accessed only by code in the same class or struct, or in a class that is derived from that class.
Accessibility:

    Cannot be accessed by object
    By derived classes


using System;
class Program
 {
  class Base
   {
     protected int num1;
   }
   class Derived : Base
    {
      public int num2;
      static void Main(string[] args)
      {
        Base ob1 = new Base();
        Derived ob2 = new Derived();
        ob2.num1 = 20;
        // Access to protected member as it is inhertited by the Derived class
        ob2.num2 = 90;
        Console.WriteLine("Number2 value {0}", ob2.num2);
        Console.WriteLine("Number1 value which is protected {0}", ob2.num1);
        Console.ReadLine();

            }

        }

    }

In the above program we try to access protected member in main it is not available as shown in the picture below that num1 is not listed in intellisense.


































4-internal
The internal access modifiers can access within the program that contain its declarations and also access within the same assembly level but not from another assembly.

Accessibility:

In same assembly (public)

    Can be accessed by objects of the class
    Can be accessed by derived classes

In other assembly (internal)

    Cannot be accessed by object
    Cannot be accessed by derived classes
5-protected internal 
Access is limited to within the class definition; This is the default access modifier type if none is formally specified.The type or member can be accessed by any code in the same assembly, but not from another assembly.A protected internal member is accessible from any class in the same assembly, including derived classes.The protected internal access modifier seems to be a confusing but is a union of protected and internal in terms of providing access but not restricting. It allows:

    Inherited types, even though they belong to a different assembly, have access to the protected internal members.
    Types that reside in the same assembly, even if they are not derived from the type, also have access to the protected internal members.

Default access

A default access level is used if no access modifier is specified in a member declaration. The following list defines the default access modifier for certain C# types:
enum: The default and only access modifier supported is public.

class: The default access for a class is private. It may be explicitly defined using any of the access modifiers.

interface: The default and only access modifier supported is public.

struct: The default access is private with public and internal supported as well.

The default access may suffice for a given situation, but you should specify the access modifier you want to use to ensure proper application behavior.


Nullable Types in c#

C# provides a special data types, the nullable types, to which you can assign normal range of values as well as null values.
Syntax:
< data_type> ? <variable_name> = null;

Here we will discuss
1. Nullable types in C#
2. Null Coalescing Operator ??  

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

The Null Coalescing Operator (??)

The null coalescing operator is used with the nullable value types and reference types. It is used for converting an operand to the type of another nullable (or not) value type operand, where an implicit conversion is possible
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 a;
        int? b = null;

        if (b == null)
        {
            a = 0;
        }
        else
        {
            a = (int)b;
        }

        Console.WriteLine("The value of a={0}", a);
        Console.ReadKey();
    }
}
The Output will be:





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

        //Using null coalesce operator ??
        a = b ?? 0;

        Console.WriteLine("The value of a={0}", a);
        Console.ReadKey();
    }
}

The Output will be same like above