C# Online Class Notes

 using System;  

public class ForExample  

    {  

      public static void Main(string[] args)  

      {  

          for(int i=1;i<=10;i++){    

            Console.WriteLine(i);    

          }    

      }  

    }





using System;  

public class WhileExample  

    {  

      public static void Main(string[] args)  

      {  

          int i=1;    

          while(i<=10)   

          {  

              Console.WriteLine(i);  

              i++;  

          }    

     }  

   }  





using System;  

public class DoWhileExample  

    {  

      public static void Main(string[] args)  

      {  

          int i = 1;  

            

          do{  

              Console.WriteLine(i);  

              i++;  

          } while (i <= 10) ;  

    

     }  

   }  




using System;  

public class BreakExample  

    {  

      public static void Main(string[] args)  

      {  

          for (int i = 1; i <= 10; i++)  

          {  

              if (i == 5)  

              {  

                  break;  

              }  

              Console.WriteLine(i);  

          }  

      }  

   }  




using System;  

namespace FunctionExample  

{  

    class Program  

    {  

        // User defined function without return type  

        public void Show() // No Parameter  

        {  

            Console.WriteLine("This is non parameterized function");  

            // No return statement  

        }  

        // Main function, execution entry point of the program  

        static void Main(string[] args)  

        {  

            Program program = new Program(); // Creating Object  

            program.Show(); // Calling Function             

        }  

    }  

}  






using System;  

namespace CallByValue  

{  

    class Program  

    {  

        // User defined function  

        public void Show(int val)  

        {  

             val *= val; // Manipulating value  

            Console.WriteLine("Value inside the show function "+val);  

            // No return statement  

        }  

        // Main function, execution entry point of the program  

        static void Main(string[] args)  

        {  

            int val = 50;  

            Program program = new Program(); // Creating Object  

            Console.WriteLine("Value before calling the function "+val);  

            program.Show(val); // Calling Function by passing value            

            Console.WriteLine("Value after calling the function " + val);  

        }  

    }  

}  

   

   

   

   

   

   

using System;  

public class ArrayExample  

{  

    public static void Main(string[] args)  

    {  

        int[] arr = new int[5];//creating array  

        arr[0] = 10;//initializing array  

        arr[2] = 20;  

        arr[4] = 30;  

  

        //traversing array  

        for (int i = 0; i < arr.Length; i++)  

        {  

            Console.WriteLine(arr[i]);  

        }  

    }  

}  





using System;  

public class ArrayExample  

{  

    static void printArray(int[] arr)  

    {  

        Console.WriteLine("Printing array elements:");  

        for (int i = 0; i < arr.Length; i++)  

        {  

              Console.WriteLine(arr[i]);  

        }  

    }

    public static void Main(string[] args)  

    {  

        int[] arr1 = { 25, 10, 20, 15, 40, 50 };  

        int[] arr2 = { 12, 23, 44, 11, 54 };  

        printArray(arr1);//passing array to function  

        printArray(arr2);  

    }  

}  




using System;  

public class MultiArrayExample  

{  

    public static void Main(string[] args)  

    {  

        int[,] arr=new int[3,3];//declaration of 2D array  

        arr[0,1]=10;//initialization  

        arr[1,2]=20;  

        arr[2,0]=30;  

  

        //traversal  

        for(int i=0;i<3;i++){  

            for(int j=0;j<3;j++){  

                Console.Write(arr[i,j]+" ");  

            }  

            Console.WriteLine();//new line at each row  

        }  

    }  

}  




using System;  

   public class Student  

    {  

        int id;//data member (also instance variable)    

        String name;//data member(also instance variable)    

         

    public static void Main(string[] args)  

        {  

            Student s1 = new Student();//creating an object of Student    

            s1.id = 101;  

            s1.name = "Sonoo Jaiswal";  

            Console.WriteLine(s1.id);  

            Console.WriteLine(s1.name);  

  

        }  

    }  

   using System;  

   public class Employee  

    {  

        public Employee()  

        {  

            Console.WriteLine("Default Constructor Invoked");  

        }  

        public static void Main(string[] args)  

        {  

            Employee e1 = new Employee();  

            Employee e2 = new Employee();  

        }  

    }  

-------------

C# Static Field

A field which is declared as static, is called static field. Unlike instance field which gets memory each time whenever you create object, there is only one copy of static field created in the memory. It is shared to all the objects.


It is used to refer the common property of all objects such as rateOfInterest in case of Account, companyName in case of Employee etc.

using System;  

   public class Account  

    {  

        public int accno;   

        public String name;  

        public static float rateOfInterest=8.8f;  

        public Account(int accno, String name)  

        {  

            this.accno = accno;  

            this.name = name;  

        }  

          

        public void display()  

        {  

            Console.WriteLine(accno + " " + name + " " + rateOfInterest);  

        }  

   }  

   class TestAccount{  

       public static void Main(string[] args)  

        {  

         Account a1 = new Account(101, "Sonoo");  

            Account a2 = new Account(102, "Mahesh");  

            a1.display();  

            a2.display();  

  

        }  

    }  




------------



Points to remember for C# static class

C# static class contains only static members.

C# static class cannot be instantiated.

C# static class is sealed.

C# static class cannot contain instance constructors.

C# static class example

Let's see the example of static class that contains static field and static method.


using System;  

   public static class MyMath  

    {  

        public static float PI=3.14f;   

        public static int cube(int n){return n*n*n;}  

    }  

   class TestMyMath{  

       public static void Main(string[] args)  

        {  

            Console.WriteLine("Value of PI is: "+MyMath.PI);  

            Console.WriteLine("Cube of 3 is: " + MyMath.cube(3));  

        }  

    }  


-----------------------------------------



C# Structs

In C#, classes and structs are blueprints that are used to create instance of a class. Structs are used for lightweight objects such as Color, Rectangle, Point etc.


Unlike class, structs in C# are value type than reference type. It is useful if you have data that is not intended to be modified after creation of struct.



using System;  

public struct Rectangle  

{  

    public int width, height;  

  

 }  

public class TestStructs  

{  

    public static void Main()  

    {  

        Rectangle r = new Rectangle();  

        r.width = 4;  

        r.height = 5;  

        Console.WriteLine("Area of Rectangle is: " + (r.width * r.height));  

    }  

}  

--------------------------


# Enum

Enum in C# is also known as enumeration. It is used to store a set of named constants such as season, days, month, size etc. The enum constants are also known as enumerators. Enum in C# can be declared within or outside class and structs.


Enum constants has default values which starts from 0 and incremented to one by one. But we can change the default value.


Points to remember

enum has fixed set of constants

enum improves type safety

enum can be traversed

C# Enum Example

Let's see a simple example of C# enum.


using System;  

public class EnumExample  

{  

    public enum Season { WINTER, SPRING, SUMMER, FALL }    

  

    public static void Main()  

    {  

        int x = (int)Season.WINTER;  

        int y = (int)Season.SUMMER;  

        Console.WriteLine("WINTER = {0}", x);  

        Console.WriteLine("SUMMER = {0}", y);  

    }  

}  


------------------------------


C# Properties

C# Properites doesn't have storage location. C# Properites are extension of fields and accessed like fields.


The Properties have accessors that are used to set, get or compute their values.


Usage of C# Properties

C# Properties can be read-only or write-only.

We can have logic while setting values in the C# Properties.

We make fields of the class private, so that fields can't be accessed from outside the class directly. Now we are forced to use C# properties for setting or getting values.

C# Properties Example

using System;  

   public class Employee  

    {  

        private string name;  

  

        public string Name  

        {  

            get  

            {  

                return name;  

            }  

            set  

            {  

                name = value;  

            }  

        }  

   }  

   class TestEmployee{  

       public static void Main(string[] args)  

        {  

            Employee e1 = new Employee();  

            e1.Name = "Sonoo Jaiswal";  

            Console.WriteLine("Employee Name: " + e1.Name);  

  

        }  

    }  

-----------------------


C# Inheritance


using System;  

   public class Employee  

    {  

       public float salary = 40000;  

   }  

   public class Programmer: Employee  

   {  

       public float bonus = 10000;  

   }  

   class TestInheritance{  

       public static void Main(string[] args)  

        {  

            Programmer p1 = new Programmer();  

  

            Console.WriteLine("Salary: " + p1.salary);  

            Console.WriteLine("Bonus: " + p1.bonus);  

  

        }  

    }  

--------------


C# Method Overloading

Having two or more methods with same name but different in parameters, is known as method overloading in C#.


The advantage of method overloading is that it increases the readability of the program because you don't need to use different names for same action.



You can perform method overloading in C# by two ways:


By changing number of arguments

By changing data type of the arguments

C# Method Overloading Example: By changing no. of arguments

Let's see the simple example of method overloading where we are changing number of arguments of add() method.


using System;  

public class Cal{  

    public static int add(int a,int b){  

        return a + b;  

    }  

    public static int add(int a, int b, int c)  

    {  

        return a + b + c;  

    }  

}  

public class TestMemberOverloading  

{  

    public static void Main()  

    {  

        Console.WriteLine(Cal.add(12, 23));  

        Console.WriteLine(Cal.add(12, 23, 25));  

    }  

}  

---------


C# Method Overriding


using System;  

public class Animal{  

    public virtual void eat(){  

        Console.WriteLine("Eating...");  

    }  

}  

public class Dog: Animal  

{  

    public override void eat()  

    {  

        Console.WriteLine("Eating bread...");  

    }  

}  

public class TestOverriding  

{  

    public static void Main()  

    {  

        Dog d = new Dog();  

        d.eat();  

    }  

}  


------------


C# Base

In C#, base keyword is used to access fields, constructors and methods of base class.


You can use base keyword within instance method, constructor or instance property accessor only. You can't use it inside the static method.


C# base keyword: accessing base class field

We can use the base keyword to access the fields of the base class within derived class. It is useful if base and derived classes have the same fields. If derived class doesn't define same field, there is no need to use base keyword. Base class field can be directly accessed by the derived class.




using System;  

public class Animal{  

    public string color = "white";  

}  

public class Dog: Animal  

{  

    string color = "black";  

    public void showColor()  

    {  

        Console.WriteLine(base.color);  

        Console.WriteLine(color);  

    }  

      

}  

public class TestBase  

{  

    public static void Main()  

    {  

        Dog d = new Dog();  

        d.showColor();  

    }  

}  



C# Polymorphism

The term "Polymorphism" is the combination of "poly" + "morphs" which means many forms. It is a greek word. In object-oriented programming, we use 3 main concepts: inheritance, encapsulation and polymorphism.


There are two types of polymorphism in C#: compile time polymorphism and runtime polymorphism. Compile time polymorphism is achieved by method overloading and operator overloading in C#. It is also known as static binding or early binding. Runtime polymorphism in achieved by method overriding which is also known as dynamic binding or late binding.



------------


C# Sealed

C# sealed keyword applies restrictions on the class and method. If you create a sealed class, it cannot be derived. If you create a sealed method, it cannot be overridden


C# Sealed class

C# sealed class cannot be derived by any class. Let's see an example of sealed class in C#.


using System;  

sealed public class Animal{  

    public void eat() { Console.WriteLine("eating..."); }  

}  

public class Dog: Animal  

{  

    public void bark() { Console.WriteLine("barking..."); }  

}  

public class TestSealed  

{  

    public static void Main()  

    {  

        Dog d = new Dog();  

        d.eat();  

        d.bark();  

  

  

    }  

}  


Output:


Compile Time Error: 'Dog': cannot derive from sealed type 'Animal'


---------


C# Abstract

Abstract classes are the way to achieve abstraction in C#. Abstraction in C# is the process to hide the internal details and showing functionality only. Abstraction can be achieved by two ways:


Abstract class

Interface

Abstract class and interface both can have abstract methods which are necessary for abstraction.


Abstract Method

A method which is declared abstract and has no body is called abstract method. It can be declared inside the abstract class only. Its implementation must be provided by derived classes. For example:


public abstract void draw();  



C# Abstract class

Data abstraction is the process of hiding certain details and showing only essential information to the user.

Abstraction can be achieved with either abstract classes or interfaces (which you will learn more about in the next chapter).


The abstract keyword is used for classes and methods:


Abstract class: is a restricted class that cannot be used to create objects (to access it, it must be inherited from another class).


Abstract method: can only be used in an abstract class, and it does not have a body. The body is provided by the derived class (inherited from).



using System;  

public abstract class Shape  

{  

    public abstract void draw();  

}  

public class Rectangle : Shape  

{  

    public override void draw()  

    {  

        Console.WriteLine("drawing rectangle...");  

    }  

}  

public class Circle : Shape  

{  

    public override void draw()  

    {  

        Console.WriteLine("drawing circle...");  

    }  

}  

public class TestAbstract  

{  

    public static void Main()  

    {  

        Shape s;  

        s = new Rectangle();  

        s.draw();  

        s = new Circle();  

        s.draw();  

    }  

}  



-----------


C# Interface

Interface in C# is a blueprint of a class. It is like abstract class because all the methods which are declared inside the interface are abstract methods. It cannot have method body and cannot be instantiated.


It is used to achieve multiple inheritance which can't be achieved by class. It is used to achieve fully abstraction because it cannot have method body.


Its implementation must be provided by class or struct. The class or struct which implements the interface, must provide the implementation of all the methods declared inside the interface.



  1. namespace MultipleInheritApplication    
  2. {    
  3.     interface calc1    
  4.     {    
  5.         int add(int a, int b);    
  6.     }    
  7.     interface calc2    
  8.     {    
  9.         int sub(int x, int y);    
  10.     }    
  11.     interface calc3    
  12.     {    
  13.         int mul(int r, int s);    
  14.     }    
  15.     interface calc4    
  16.     {    
  17.         int div(int c, int d);    
  18.     }    
  19.     class Calculation : calc1, calc2, calc3, calc4    
  20.     {    
  21.         public int result1;    
  22.         public int add(int a, int b)    
  23.         {    
  24.             return result1 = a + b;    
  25.         }    
  26.         public int result2;    
  27.         public int sub(int x, int y)    
  28.         {    
  29.             return result2 = x - y;    
  30.         }    
  31.         public int result3;    
  32.         public int mul(int r, int s)    
  33.         {    
  34.             return result3 = r * s;    
  35.         }    
  36.         public int result4;    
  37.         public int div(int c, int d)    
  38.         {    
  39.             return result4 = c / d;    
  40.         }    
  41.      
  42.         class Program    
  43.         {    
  44.             static void Main(string[] args)    
  45.             {    
  46.                 Calculation c = new Calculation();    
  47.                 c.add(8, 2);    
  48.                 c.sub(20, 10);    
  49.                 c.mul(5, 2);    
  50.                 c.div(20, 10);    
  51.                 Console.WriteLine("Multiple Inheritance concept Using Interfaces :\n ");    
  52.                 Console.WriteLine("Addition: " + c.result1);    
  53.                 Console.WriteLine("Substraction: " + c.result2);    
  54.                 Console.WriteLine("Multiplication :" + c.result3);    
  55.                 Console.WriteLine("Division: " + c.result4);    
  56.                 Console.ReadKey();    
  57.             }    
  58.         }    
  59.     }    

-----------

try

{

  int[] myNumbers = {1, 2, 3};

  Console.WriteLine(myNumbers[10]);

}

catch (Exception e)

{

  Console.WriteLine(e.Message);

}



----------


try

{

  int[] myNumbers = {1, 2, 3};

  Console.WriteLine(myNumbers[10]);

}

catch (Exception e)

{

  Console.WriteLine("Something went wrong.");

}

--------------

Finally

The finally statement lets you execute code, after try...catch, regardless of the result:




try

{

  int[] myNumbers = {1, 2, 3};

  Console.WriteLine(myNumbers[10]);

}

catch (Exception e)

{

  Console.WriteLine("Something went wrong.");

}

finally

{

  Console.WriteLine("The 'try catch' is finished.");

}

--------------


The throw keyword

The throw statement allows you to create a custom error.


The throw statement is used together with an exception class. There are many exception classes available in C#: ArithmeticException, FileNotFoundException, IndexOutOfRangeException, TimeOutException, etc:


Example

static void checkAge(int age)

{

  if (age < 18)

  {

    throw new ArithmeticException("Access denied - You must be at least 18 years old.");

  }

  else

  {

    Console.WriteLine("Access granted - You are old enough!");

  }

}


static void Main(string[] args)

{

  checkAge(15);

}


-------

checkAge(20);



--------------


protected void btnSubmit_Click(object sender,EventArgs e)

{

Response.Write(txtName.Text + "</br>");


Response.Write(lstLocation.SelectedItem.Text + "</br>");


lblName.Visible = false; 

txtName.Visible = false; 

lstLocation.Visible = false;

chkC.Visible = false; 

chkASP.Visible = false; 

rdFemale.Visible = false;

btnSubmit.Visible = false;

}


Comments

Popular Posts