C#DOTNETCONSOLEAPPLICATION

C#DOTNETCONSOLEAPPLICATION

===================================

Namespace:

1) it is a Collection of names wherein each name is Unique.

2) They form the logical boundary for a Group of classes.

3) Namespace must be specified in Project-Properties.

Assembly:

1) It is an Output Unit.

2) It is a unit of Deployment & a unit of versioning.

3) Assemblies contain MSIL code.

4) Assemblies are Self-Describing. [e.g. metadata,manifest]

5)An assembly is the primary building block of a .NET Framework application.

6) It is a collection of functionality that is built, versioned, and deployed as a single implementation unit (as one or more files).

7) All managed types and resources are marked either as accessible only within their implementation unit, or by code outside that unit.

Difference between NameSpace and Assembly

A .Net Namespace provides the fundamental unit of logical code grouping while an assembly provides a fundamental unit of physical code grouping.

Namespaces is a logical group of related classes that can be used by any other language targeting the Microsoft .Net framework . It is more used for logical organization of your classes. Namespaces are a way of grouping type names and reducing the chance of name collisions.

================================= 

c#.net

 

NET

. NET is a free, open-source developer platform created by Microsoft. It allows developers to build various types of applications, such as web, desktop, mobile, cloud, gaming, IoT, and more. The platform includes a wide range of tools, libraries, and programming languages like C#, F#, and Visual Basic.

 

Key Components of .NET:

· .NET Runtime: Manages program execution, including memory management, garbage collection, and security.

· .NET Framework: The original version for Windows applications.

· .NET Core: A cross-platform, modular version of .NET for building applications on Windows, macOS, and Linux.

· ASP.NET: A framework for building web applications and services.

· Entity Framework (EF): An Object-Relational Mapping (ORM) tool to work with databases.

· Blazor: A framework for building interactive web UIs using C# instead of JavaScript.

· Advantages of .NET:

· Cross-platform support: With .NET Core and .NET 5+, applications can run on multiple operating systems.

· Performance: Highly optimized for speed and scalability.

· Language versatility: Supports multiple programming languages.

· Tooling and Integration: Seamless integration with Visual Studio and other Microsoft tools.

 

Ñ C# is pronounced "C-Sharp".

 

Ñ It is an object-oriented programming language created by Microsoft that runs on the .NET Framework.

 

Ñ C# has roots from the C family, and the language is close to other popular languages like C++ and Java.

 

Ñ The first version was released in year 2002. The latest version, C# 8, was released in September 2019.

 

 

 

 

 C# is used for:

§ Mobile applications

§ Desktop applications

§ Web applications

§ Web services

§ Web sites

§ Games

§ Database applications

Why Use C#?

 

It is one of the most popular programming languages in the world.

It is easy to learn and simple to use.

It has a huge community support.

C# is an object-oriented language which gives a clear structure to programs and allows code to be reused, lowering development costs.

As C# is close to C, C++ and Java, it makes it easy for programmers to switch to C# or vice versa.

C# Variables

 

1.compiler

2.interpreter

3.assembler

Ñ Father of C#.net- Anders Hejlsberg

Ñ C# is used for: Mobile applications Desktop applications Web applications Web services Web sites Games Database applications

First Program

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace first

{

    internal class Program

    {

        static void Main(string[] args)

        {

            Console. WriteLine("Welcome to c#");

        }

    }

}

 

Second Program

 

namespace Second

{

    internal class Program

    {

        static void Main(string[] args)

        {

            String a = "Hello";

            Console. WriteLine(a);

        }

    }

}

 

======================================================================

 

 

Datatypes

· int - stores integers (whole numbers), without decimals, such as 123 or -123

· double - stores floating point numbers, with decimals, such as 19.99 or -19.99

· char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes

· string - stores text, such as "Hello World". String values are surrounded by double quotes

· bool - stores values with two states: true or false

 

 

 

Tokens

Token refers to a fundamental unit of code that the compiler uses to understand the structure and meaning of the source code. Here are some examples of tokens in C#:

1. Keywords: These are reserved words with predefined meanings in the C# language, such as class, if, for, while, int, etc.

2. Identifiers: These are names given to entities in a program, such as variables, functions, classes, etc. Identifiers can include letters, digits, and underscores, but must follow certain naming conventions and cannot be a C# keyword.

 3. Literals: These are constant values explicitly specified in the code. For example, 42 is an integer literal, "Hello" is a string literal, true is a Boolean literal, etc.

4. Operators: These are symbols used to perform operations on variables or values, such as +, -, *, /, &&, ||, ==, =, etc.

5. Punctuation Marks: These include symbols like parentheses (), braces {}, square brackets [], semicolons; commas, periods., etc., used for grouping, separating, or terminating code elements.

 

 

OPERATORS

The followings are the operators in c#:

1. Arithmetic operators

2. Assignment operators

3. Logical operators

4. Conditional operators

5. Relational operators

6. Increment operator

7. Decrement operators

 

Arithmetic operators

+ - * / %

using System;

using System. Collections. Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace arithmetic

{

    internal class Program

    {

        static void Main(string[] args)

        {

            int a = 20;

            int b = 10;

            Console. WriteLine("SUM=" + (a + b));

            Console. WriteLine("difference=" + (a - b));

            Console. WriteLine("product=" + (a * b));

            Console. WriteLine("division=" + (a / b));

            Console. WriteLine("modulus=" + (a % b));

 

 

        }

    }

}

======================================================================

 

Assignment operators

+= -= *= /= %=

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace assignment operator

{

    internal class Program

    {

        static void Main(string[] args)

        {

            int a = 20;

            a += 3;

            Console. WriteLine(a);

            a -= 2;

            Console. WriteLine(a);

            a *= 3;

            Console. WriteLine(a);

            a /= 4;

            Console. WriteLine(a);

            a %= 2;

            Console. WriteLine(a);

        }

    }

}

======================================================================

 

Conditional operators

 

Ø Syntax: (condition)? True: false;

Console. WriteLine("Enter 2 numbers:");

 

 Int a=Convert.ToInt32(Console.ReadLine());

 int b=Convert.ToInt32(Console.ReadLine());

int max = (a > b) ? a : b; Console. WriteLine("big= “+max);

======================================================================

 

Logical operators

( AND &&, OR || , NOT EQUALTO !=)

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace logical operators

{

    internal class Program

    {

        static void Main(string[] args)

        {

            

            Console. WriteLine("Enter 4 numbers");

 

            int a = Convert.ToInt32(Console.ReadLine());

 

            int b = Convert.ToInt32(Console.ReadLine());

 

            int c = Convert.ToInt32(Console.ReadLine());

            int d = Convert.ToInt32(Console.ReadLine());

 

 

 

            if ((a > b) && (a > c) && (a > d))

 

                Console. WriteLine("big= " + a);

 

            else if ((b > a) && (b > c) && (b > d))

 

                Console. WriteLine("big= " + b);

 

            else if (c > d)

 

                Console. WriteLine("big= " + c);

 

            else

 

                Console. WriteLine("big=" + d);

        }

    }}

======================================================================

 

Logical OR

Console. WriteLine("Enter a character");

char a = Convert.ToChar(Console.ReadLine());’

 if((a=='a' ) || (a=='e') || (a=='i') || (a=='o') ||(a=='u'))

{

Console. WriteLine("Vowels");

}

else { Console. WriteLine("Not a vowel"); }

Notequal

Console. WriteLine("Enter a number");

 

            int a = Convert.ToInt32(Console.ReadLine());

            if (a % 2 == 0)

                Console. WriteLine("even");

            if (a % 2 != 0)

                Console. WriteLine("ODD");

======================================================================

 

Increment/Decrement Operators

 

            

Console. WriteLine("Enter a number");

            int a = Convert.ToInt32(Console.ReadLine());

            a++; //increment

            Console. WriteLine(a);

a--; //decrement

            Console. WriteLine(a);

======================================================================

 

Relational operators

> ,<,>=,<=

Console. WriteLine("enter two numbers");

int a = Convert.ToInt32(Console.ReadLine());

int b = Convert.ToInt32(Console.ReadLine());

if (a > b)

    Console. WriteLine("big=" + a);

 else

    Console. WriteLine("big=" + b);

======================================================================

Control Structures

1. If

Syntax:

if(condition)

{

//statements;

}

 

 

    Console.WriteLine("enter two numbers");

    int a = Convert.ToInt32(Console.ReadLine());

            

    if (a > 0)

        Console.WriteLine("POSITIVE");

    else

        Console.WriteLine("NEGATIVE");

}

 

 

 

            Console.WriteLine("Enter 2 numbers:");

            int a = Convert.ToInt32(Console.ReadLine());

            int b = Convert.ToInt32(Console.ReadLine());

            if (a > b)

            {

                Console.WriteLine(a+" is the bigger number");

            }

            else

            {

                Console.WriteLine(b+" is the bigger number");

            }

 

            

            

            

        }

 

 

=======================================================

static void Main(string[] args)

{

 

    Console.WriteLine("Enter 2 numbers:");

    int a = Convert.ToInt32(Console.ReadLine());

    int b = Convert.ToInt32(Console.ReadLine());

    Console.WriteLine("Enter your choice:");

    string c = Console.ReadLine();

 

    if (c == "+")

    {

        Console.WriteLine(a + b);

    }

    else if (c == "-")

    {

 

        Console.WriteLine(a - b);

    }

 

    else if (c == "*")

    {

        Console.WriteLine(a * b);

 

    }

    else if(c=="/")

    {

        Console.WriteLine(a / b);

    }

    else

    {

        Console.WriteLine("Invalid");

    }

                        

            

            

}

 

 

 

static void Main(string[] args)

{

 

    Console.WriteLine("Enter a letter:");

    char c = Convert.ToChar(Console.ReadLine());

            

            

           

 

    if ((c == 'a')||(c =='A'))

    {

        Console.WriteLine(c+ " is Vowel");

    }

    else if ((c == 'e') || (c == 'E'))

    {

 

        Console.WriteLine(c + " is Vowel");

    }

 

    else if ((c == 'i') || (c == 'I'))

    {

        Console.WriteLine(c + " is Vowel");

 

    }

    else if ((c == 'o') || (c == 'O'))

    {

        Console.WriteLine(c + " is Vowel");

    }

    else if ((c == 'u') || (c == 'U'))

    {

        Console.WriteLine(c + " is Vowel");

    }

    else

    {

        Console.WriteLine(c + " is not a Vowel");

    }           

            

            ============================================================

 

static void Main(string[] args)

{

 

    Console.WriteLine("Enter a number:");

    int c = Convert.ToInt32(Console.ReadLine());

    switch (c)

    {

        case 1:

            Console.WriteLine("One");

            break;

        case 2:

            Console.WriteLine("Two");

            break;

        case 3:

            Console.WriteLine("Three");

            break;

        case 4:

            Console.WriteLine("Four");

            break;

        case 5:

            Console.WriteLine("Five");

            break;

        default:

            Console.WriteLine("Invalid");

            break;

    }

            

            =============================================================

 

 

static void Main(string[] args)

{

 

    Console.WriteLine("Enter two number:");

    int c = Convert.ToInt32(Console.ReadLine());

    int d = Convert.ToInt32(Console.ReadLine());

    Console.WriteLine("Enter your choice");

    string a = Console.ReadLine();

    switch (a)

    {

        case "+":

            Console.WriteLine(c+d);

            break;

        case "-":

            Console.WriteLine(c-d);

            break;

        case "*":

            Console.WriteLine(c*d);

            break;

        case "/":

            Console.WriteLine(c/d);

            break;

                

        default:

            Console.WriteLine("Invalid");

            break;

    }

            

            

           ============================================================

Console.WriteLine("Enter a letter");

 char a = Convert.ToChar(Console.ReadLine());

 

 switch (a)

 {

     case 'a':

     case 'A':

     case 'e':

     case 'E':

     case 'i':

     case 'I':

     case 'o':

     case 'O':

     case 'u':

     case 'U':

         Console.WriteLine("VOWELS");

         break;

     default:

         Console.WriteLine("Not a Vowel");

         break;

 }

 

 

    internal class Program

    {

        static void Main(string[] args)

        {

            int i = 0;

            while (i <= 10)

            {

                Console.WriteLine(i);

                i++;

            }

        }

    }

}

 

 

        static void Main(string[] args)

        {

            int i = 10;

            while (i >= 0)

            {

                Console.WriteLine(i);

                i--;

            }

        }

    }

}

 

 

        static void Main(string[] args)

        {

            int i = 19;

            while (i >= 0)

            {

                Console.WriteLine(i);

                i-=2;

            }

        }

    }

}

 

        static void Main(string[] args)

        {

            int i = 19;

            do

            {

                Console.WriteLine(i);

                i -= 2;

            }

            while (i >= 0);

        }

    }

}

 

 

 

 

 

    internal class Program

    {

        static void Main(string[] args)

        {

            for (int i = 0; i<=20;i++)

                {

                Console.WriteLine(i);

            }

           

        }

    }

}

 

 

        static void Main(string[] args)

        {

            for (int i = 0; i<=50;i+=7)

                {

                Console.WriteLine(i);

            }

           

        }

    }

}

 

 

        static void Main(string[] args)

        {

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

                {

                Console.WriteLine(i+"*7="+(i*7) );

            }

           

        }

    }

}

 

            Console.WriteLine("Enter a number");

            int a =Convert.ToInt32(Console.ReadLine());

 

            

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

                {

                Console.WriteLine(i+"*"+a+"="+(i*a) );

            }

           

        }

    }

}

 

 

                                                        OR

 

            Console.WriteLine("Enter a number");

            int n =Convert.ToInt32(Console.ReadLine());

 

            

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

                {

                //Console.WriteLine(i+"*"+a+"="+(i*a) );

                Console.WriteLine("{0}*{1}={2}", i, n, i * n);

            }

           =========================================================================

 

        static void Main(string[] args)

        {

            Console.WriteLine("Enter three number");

            int n =Convert.ToInt32(Console.ReadLine());

            int m = Convert.ToInt32(Console.ReadLine());

            int l = Convert.ToInt32(Console.ReadLine());

            int a = n * m * l;

 

 

 

            Console.WriteLine("{0}*{1}*{2}={3}",n,m,l,a);

            

           

        }

    }

}

 

        static void Main(string[] args)

        {

            int[] Arrayint = { 10, 44, 22, 15 };

 

            foreach (int m in Arrayint)

 

            {

 

                Console.WriteLine("" + m);

 

            }

        }

    }

}

 

static void Main(string[] args)

{

    String[] Arrays = { "hello", "what", "welcome", "thankyou" };

 

    foreach (String m in Arrays)

 

    {

 

        Console.WriteLine("" + m);

 

    }

 

        string[] cars = { "Volvo", "BMW", "Ford", "Mazda" ,"maruthi"};

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

        {

            Console.WriteLine(cars[i]);

        }

       Console.WriteLine(cars.Length);

        

    }

}

        Console.WriteLine("Enter the numbers");

 

        int[] a = new int[5];

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

        {

            a[i] = Convert.ToInt32(Console.ReadLine());

 

        }

        Console.WriteLine("The Elements are");

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

        {

            Console.WriteLine(a[i]);

        }

    }

}

 

            Console.WriteLine("Enter the numbers");

            int sum = 0;

            int[] a = new int[5];

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

            {

                

                a[i] = Convert.ToInt32(Console.ReadLine());

                sum += a[i];

            }

            Console.WriteLine("The Elements are");

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

            {

                Console.WriteLine(a[i]);

 

            }

            Console.WriteLine("Sum =" + sum);

;        }

 

 

 

C# Type Casting T

Type casting is when you assign a value of one data type to another type.

 In C#, there are two types of casting:

1. Implicit Casting (automatically) - converting a smaller type to a larger type size. char -> int -> long -> float -> double

 

    static void Main(string[] args)

    {

        int myInt = 9;

 

        double myDouble = myInt;  // Automatic casting: int to double

 

        Console.WriteLine(myInt);

 

        Console.WriteLine(myDouble);

    }

}

 

. Explicit Casting (manually) - converting a larger type to a smaller size type. double -> float -> long -> int -> char

 

static void Main(string[] args)

 {

 

     int myInt = 10;

 

     double myDouble = 5.25;

 

     bool myBool = true;

 

     Console.WriteLine(Convert.ToString(myInt));    // Convert int to string

 

     Console.WriteLine(Convert.ToDouble(myInt));    // Convert int to double

 

     Console.WriteLine(Convert.ToInt32(myDouble));  // Convert double to int

 

     Console.WriteLine(Convert.ToString(myBool));

 

 }

 

Date and Time

static void Main(string[] args)

 {

 

     Console.WriteLine(DateTime.Now);

 

     Console.WriteLine("date=" + DateTime.Now);

 

     Console.WriteLine("date=" + DateTime.Now.ToLongDateString());

 

     Console.WriteLine("date=" + DateTime.Now.ToShortDateString());

 

     Console.WriteLine("date=" + DateTime.Now.ToLongTimeString());

 

     Console.WriteLine("date=" + DateTime.Now.Year);

 

     Console.WriteLine("date=" + DateTime.Now.Month);

 

     Console.WriteLine("date=" + DateTime.Now.Day);

 

     Console.WriteLine("date=" + DateTime.Now.Hour);

     Console.WriteLine("date=" + DateTime.Now.Minute);

 

     Console.WriteLine("date=" + DateTime.Now.Second);

 

 }

String Properties

 

    static void Main(string[] args)

    {

 

        string str = "TechnoparkTrivandrum";

 

        Console.WriteLine(str);

 

        Console.WriteLine("length=" + str.Length);

 

        Console.WriteLine(str.Substring(5));

 

        Console.WriteLine(str.Substring(3, 7));

 

        Console.WriteLine(str.Remove(3, 4));

 

        Console.WriteLine(str.Replace("i", "z"));

 

        Console.WriteLine(str.PadLeft(40, '*'));

 

        Console.WriteLine(str.PadRight(40, '*'));

 

    }

}

· Meta Data- data about data

 

 

 

Math Properties

Console.WriteLine(Math.PI);

 

Console.WriteLine(Math.Max(5, 10));

 

Console.WriteLine(Math.Min(5, 10));

 

Console.WriteLine(Math.Sqrt(64));

 

Console.WriteLine(Math.Abs(-4.7));

 

Console.WriteLine(Math.Round(9.99));

Console.WriteLine(Math.Floor(12.6));

============================================================================

LINQ(Language Integrated Query) Array methods, such as Min, Max, and Sum, can be found in the System.Linq namespace.

static void Main(string[] args)

{

 

    int[] myNumbers = { 5, 1, 8, 9 };

 

    Console.WriteLine(myNumbers.Max());  // returns the largest value

    Console.WriteLine(myNumbers.Min());  // returns the smallest value

 

    Console.WriteLine(myNumbers.Sum());  // returns the sum of elements

}

 

 

            int[] arr = new int[5];

            Console.WriteLine("Enter 5 elements");

            for (int i = 0; i < 5; i++)

            {

                arr[i] = Convert.ToInt32(Console.ReadLine());

            }

            var q = from a in arr

                    where a > 5

                    orderby a ascending

                    select a;

            Console.WriteLine("Numbers are");

            foreach (int a in q)

            {

                Console.WriteLine(a);

 

            }

 


============================================================================

C# Methods: A method is a block of code which only runs when it is called.

 You can pass data, known as parameters, into a method.

Methods are used to perform certain actions, and they are also known as functions.

Why use methods?------- To reuse code: define the code once, and use it many times.

 

    internal class Program

    {

        

        static void Main(string[] args)

        {

            MyMethod();

            MyMethod();

            MyMethod();

        }

        static void MyMethod()

 

        {

 

            Console.WriteLine("I just got executed!");

 

        }

    }

}

        static void Main(string[] args)

        {

            MyMethod();

            MyMethod();

            MyMethod1("Devi");

            MyMethod1("RAHUL");

            Console.WriteLine( "Sum is " +sum(5, 6));

 

            Console.WriteLine(sum(9, 6));

            Console.WriteLine("Enter two numbers");

            int c = Convert.ToInt32(Console.ReadLine());

            int d = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine(sum(c, d));

            Console.WriteLine(area(5));

 

        }

        static void MyMethod()

 

        {

 

            Console.WriteLine("I just got executed!");

 

        }

        static void MyMethod1(string fname)

 

        {

 

            Console.WriteLine(fname + " KRISHNA");

 

        }

        static int sum(int a, int b)

 

        {

 

            return a + b;

 

        }

        static double area(double radius)

 

        {

 

            return Math.PI * radius * radius;

 

        }

    }

}

 

Homework

internal class Program

 {

     static int sum(int c,int d)

     {

         return c + d;

     }

     static int subt(int c,int d)

     {

         return (c - d);

     }

     static int multi(int c, int d)

     {

         return c * d;

     }

     static int div(int c, int d) {

         return c / d;

     }

 

     static void Main(string[] args)

     {

         Console.WriteLine("Enter two numbers");

         int a = Convert.ToInt32(Console.ReadLine());

         int b = Convert.ToInt32(Console.ReadLine());

            

         Console.WriteLine("Sum is "+sum(a,b));

         Console.WriteLine("Differencs is "+subt(a,b));

         Console.WriteLine("Product is "+multi(a,b));

         Console.WriteLine("Division ans is "+div(a,b);

}

Array biggest element

 

internal class Program

{

    static void Main(string[] args)

    {

        int[] a = { 10, 44, 22, 15 };

        int biggest = 0;

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

        {

            if(a[i] >=biggest)

                biggest = a[i];

 

                

 

 

        }

        Console.WriteLine("Biggest number is:" +biggest);

    }

}

MultiDImensional Array / Two-Dimensional Array

 

Matrix Addition

    static void Main(string[] args)

    {

        Console.WriteLine("enter the size");

        int n = Convert.ToInt32(Console.ReadLine());

        int[,] a = new int[n, n];

        int[,] b = new int[n, n];

        int[,] c = new int[n, n];

        Console.WriteLine("enter array element of a");

            

        for (int i = 0; i < n; i++)

        {

            for (int j = 0; j < n; j++)

            {

                a[i, j] = Convert.ToInt32(Console.ReadLine());

            }

        }

        Console.WriteLine("enter array element of b");

 

        for (int i = 0; i < n; i++)

        {

            for (int j = 0; j < n; j++)

            {

                b[i, j] = Convert.ToInt32(Console.ReadLine());

            }

        }

        Console.WriteLine("Result = ");

 

        for (int i = 0; i < n; i++)

        {

            for (int j = 0; j < n; j++)

            {

                c[i, j] = a[i, j]+ b[i, j];

            }

        }

          

 

        for (int i = 0; i < n; i++)

        {

            for (int j = 0; j < n; j++)

            {

                Console.WriteLine(c[i,j]);

            }

        }

    }

 

Array Sorting

static void Main(string[] args)

 {

 

     int[] a = new int[5];

     Console.WriteLine("enter five numbers");

     for (int i = 0; i < 5; i++)

         a[i] = Convert.ToInt32(Console.ReadLine());

     Console.WriteLine("Ascending is : ");

     Array.Sort(a);

     for (int i = 0; i < 5; i++)

         Console.WriteLine(a[i]);

     Console.WriteLine("descending is:");

     Array.Reverse(a);

     for (int i = 0; i < 5; i++)

         Console.WriteLine(a[i]);

 

 }

Collection class

Array List

int i;

ArrayList a1 = new ArrayList();

Console.WriteLine("Enter ArrayList Limit");

int a = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("Enter Element");

for (i = 0; i < a; i++)

{

    a1.Add(Console.ReadLine());

}

Console.WriteLine("Elements are");

foreach (var c in a1)

{

    Console.WriteLine(c);

}

Threading

Thread is a unit process

Thread.Start

static void function()

{

    for (int i = 11; i < 20; i++)

    {

        Console.WriteLine(i);

    }

}

static void Main(string[] args)

{

    ThreadStart childthread = new ThreadStart(function);

    Thread obj = new Thread(childthread);

    obj.Start();

    {

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

        {

            Console.WriteLine(i);

        }

    }

Thread.Sleep

    static void function()

    {

        for (int i = 11; i < 20; i++)

        {

            Console.WriteLine(i);

        }

    }

    static void Main(string[] args)

    {

        ThreadStart childthread = new ThreadStart(function);

        Thread obj = new Thread(childthread);

        obj.Start();

        Thread.Sleep(1000);

        {

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

            {

                Console.WriteLine(i);

            }

        }

    }

}

What is a IL?

 

(IL)Intermediate Language is also known as MSIL (Microsoft Intermediate Language) or CIL

(Common Intermediate Language). All .NET source code is compiled to IL. This IL is then

converted to machine code at the point where the software is installed, or at run-time by a Just-InTime (JIT) compiler.

 

What is a CLR?

 

Full form of CLR is Common Language Runtime and it forms the heart of the .NET framework

.All Languages have runtime and its the responsibility of the runtime to take care of the code execution of the program.

For example VC++ has MSCRT40.DLL,VB6 has MSVBVM60.DLL , Java has Java Virtual Machine etc. Similarly .NET has CLR.

Following are the responsibilities of CLR

·  Garbage Collection :- CLR automatically manages memory thus eliminating memory leakes. When objects are not referred GC automatically releases those memory thus providing efficient memory management.

·  Code Access Security :- CAS grants rights to program depending on the security configuration of the machine.Example the program has rights to edit or create a new file but the security configuration of machine does not allow the program to delete a file.CAS will take care that the code runs under the environment of machines security configuration.

·  Code Verification :- This ensures proper code execution and type safety while the code runs.It prevents the source code to perform illegal operation such as accessing invalid memory locations etc.

·  IL( Intermediate language )-to-native translators and optimizer’s :- CLR uses JIT and compiles the IL code to machine code and then executes. CLR also determines depending on platform what is optimized way of running the IL code.

 

What is a CTS?

 

In order that two language communicate smoothly CLR has CTS (Common Type System).

Example in VB you have “Integer” and in C++ you have “long” these datatypes are not compatible so the interfacing between them is very complicated.

 In order that two different languages can communicate Microsoft introduced Common Type System. So “Integer” datatype in VB6 and “int” datatype in C++ will convert it to System.int32 which is datatype of CTS.CLS which is covered in the coming question is subset of CTS.

 

What is a CLS(Common Language Specification)?

 This is a subset of the CTS which all .NET languages are expected to support.

It was always a dream of microsoft to unite all different languages in to one umbrella and CLS is one step towards that.

Microsoft has defined CLS which are nothing but guidelines that language to follow so that it can communicate with other .NET languages in a seamless manner

 

1. What is C#?

Answer: C# (pronounced "C-sharp") is a modern, object-oriented programming language developed by Microsoft as part of the .NET platform. It is designed to be simple, efficient, and flexible, providing language constructs that help to build robust and secure applications.

2. What is the .NET Framework?

Answer: The .NET Framework is a software framework developed by Microsoft that provides a runtime environment for building, deploying, and running applications on Windows. It includes the Common Language Runtime (CLR) for execution and a large class library (Base Class Library) that supports various types of applications like Windows, web, and mobile.

3. Explain the difference between managed code and unmanaged code.

Answer: Managed code is code that runs under the control of the CLR, which provides features like garbage collection, type checking, and exception handling. Unmanaged code is executed directly by the operating system outside the CLR, such as applications written in C++.

4. What is the Common Language Runtime (CLR)?

Answer: The CLR is the runtime environment in the .NET Framework that manages the execution of .NET programs. It provides memory management, security, exception handling, and garbage collection, among other services.

5. What are the main pillars of object-oriented programming (OOP)?

Answer:

Class Class is a group of similar objects. Class is a way to bind data describing an entity and appreciated function together. To create a class, use the class keyword. A Class is a blueprint of a data type. It is actually a collection of objects. It contains objects and the definition for the operation that needs to be performed on that object.

Object – It is an instance of a class.

Syntax -- Classname objectname= new classname();

namespace object1

{ class car

    {

       public String colour = "Red";

 

    }

    internal class Program

    {

        static void Main(string[] args)

        {

            car obj = new car();

            Console.WriteLine(obj.colour);

 

        }

    }

}

 

Encapsulation: Bundling data and methods that operate on the data within a single unit (class).

Inheritance: Allowing a new class to inherit properties and behavior from an existing class.

Inheritance (Derived and Base Class)

 In C#, it is possible to inherit fields and methods from one class to another.

We group the "inheritance concept" into two categories: Derived Class (child) - the class that inherits from another class Base Class (parent) - the class being inherited from To inherit from a class, use the : symbol. In C#, there are several types of inheritance:

In C#, there are 4 types of inheritance

1.Single Inheritance---One base class and one child class

 

2.Multi-Level

3.Hierarchial --- One parent and multiple child

4.Hybrid Inheritance

Syntax: class derived-class : base-class { // methods and fields }

 

 

 

Single inheritance

namespace inheritance

{

    class vehicle

    {

    public void run()

        {

            Console.WriteLine("Running");

        }

    }

    class car :vehicle

    {

    

    

    public void drive()

        {

            Console.WriteLine("MAruthi");

        }

    

    }

 

 

    internal class Program

    {

        static void Main(string[] args)

        {

            car obj = new car();    

            obj.run();

            obj.drive();

        }

    }

}

Multi-Level Inheritance

namespace inheritance

{

    class vehicle

    {

    public void run()

        {

            Console.WriteLine("Running");

        }

    }

    class car :vehicle

    {

    

    

    public void drive()

        {

            Console.WriteLine("MAruthi");

        }

    

    }

    class benz : car

 

    {

        public void music()

        {

            Console.WriteLine("Music is PLaying");

        }

    }

 

 

    internal class Program

    {

        static void Main(string[] args)

        {

            benz obj = new benz();    

            obj.run();

            obj.drive();

            obj.music();

        }

    }

}

Hierarchial Inheritance

 

namespace inheritance

{

    class vehicle

    {

    public void run()

        {

            Console.WriteLine("Running");

        }

    }

    class car :vehicle

    {

    

    

    public void drive()

        {

            Console.WriteLine("MAruthi");

        }

    

    }

   class bus :vehicle

    {

        public void horn()

        {

            Console.WriteLine("Sound horn");

        }

    }

 

    internal class Program

    {

        static void Main(string[] args)

        {

            bus obj = new bus();    

            car obj1 = new car();

            obj1.drive();

            obj1.run();

            obj.horn();

            obj.run();

 

        }

    }

}

Hybrid Inheritance—Combination of hierarchial and multi level inheritance

namespace inheritance

{

    class vehicle

    {

    public void run()

        {

            Console.WriteLine("Running");

        }

    }

    class car :vehicle

    {

    

    

    public void drive()

        {

            Console.WriteLine("MAruthi");

        }

    

    }

   class bus :vehicle

    {

        public void horn()

        {

            Console.WriteLine("Sound horn");

        }

    }

    class volvo : bus

    {

        public void travel()

        {

            Console.WriteLine("Travel around");

        }

    }

 

    internal class Program

    {

        static void Main(string[] args)

        {

            volvo obj = new volvo();    

            car obj1 = new car();

            obj1.drive();

            obj1.run();

            obj.horn();

            obj.run();

            obj.travel();

 

        }

    }

}

 

Polymorphism(many forms): Providing the ability to call the same method on different objects and have each of them respond in their own way.

Two types :

1 Function overloading

· No of parameters

· Type of parameter

· namespace polymorphism

· {

·     public class TestData

· 

· 

· 

·     {

· 

·         public int Add(int a, int b, int c)

· 

·         {

· 

·             return a + b + c;

· 

· 

· 

·         }

· 

·         public int Add(int a, int b)

· 

·         {

· 

·             return a + b;

· 

·         }

· 

·     }

·     internal class Program

·     {

· 

·         static void Main(string[] args)

·         {

·             TestData data = new TestData();

·            Console.WriteLine( data.Add(1, 2, 3));

·             Console.WriteLine(data.Add(2, 5));

·         }

·     }

· Type of parameter

 

 

namespace polymorphism

· {

·     public class TestData

· 

· 

· 

·     {

· 

·         public float Add(float a, float b, float c)

· 

·         {

· 

·             return a + b + c;

· 

· 

· 

·         }

· 

·         public int Add(int a, int b,int c)

· 

·         {

· 

·             return a + b+c;

· 

·         }

·         public double Add(double a, double b, double c) {

·             return a * b * c;

·         }

· 

·     }

·     internal class Program

·     {

· 

·         static void Main(string[] args)

·         {

·             TestData data = new TestData();

·            Console.WriteLine( data.Add(1.2f, 2.5f, 3.8f));

·             Console.WriteLine(data.Add(2, 5,6));

·             Console.WriteLine(data.Add(2.33,5.6,7.1));

·         }

·     }

· }

 

2.Function Overriding ----- Method overriding can be done using inheritance. With method overriding it is possible for the base class and derived class to have the same method name and same something.

namespace methodOverriding

{

    class baseClass

 

    {

 

 

 

        // show() is 'virtual' here

 

        public virtual void show()

 

        {

 

            Console.WriteLine("Base class");

 

        }

 

    }

 

 

 

 

 

    // class 'baseClass' inherit

 

    // class 'derived'

 

    class derived : baseClass

 

    {

 

 

 

        //'show()' is 'override' here

 

        public override void show()

 

        {

 

            Console.WriteLine("Derived class");

 

        }

 

    }

    internal class Program

    {

        static void Main(string[] args)

        {

            derived obj = new derived();

            obj.show();

        }

    }

}

 

 

Abstraction: Abstraction is a concept of simplifying a real-world object into its essential features without including background details

Hiding the complexity of code by exposing only the necessary parts.

Abstract Classes · An abstract class is declared with the help of abstract keyword. ·

 In C#, you are not allowed to create objects of the abstract class. Or in other words, you cannot use the abstract class directly with the new operator. ·

Class that contains the abstract keyword with some of its methods(not all abstract method) is known as an Abstract Base Class. ·

 Class that contains the abstract keyword with all of its methods is known as pure Abstract Base Class

You are not allowed to declare the abstract methods outside the abstract class. ·

 You are not allowed to declare abstract class as Sealed Class.

namespace Abstraction

{

    abstract class Shape

    {

        // Abstract method (does not have a body)

        public abstract void Draw();

 

        // Non-abstract method

        public void Display()

        {

            Console.WriteLine("This is a shape.");

        }

    }

 

    // Derived class

    class Circle : Shape

    {

        public override void Draw()

        {

            Console.WriteLine("Drawing a Circle.");

        }

    }

    // Another derived class

    class Rectangle : Shape

    {

        public override void Draw()

        {

            Console.WriteLine("Drawing a Rectangle.");

        }

    }

    internal class Program

    {

        static void Main(string[] args)

        {

            Shape circle = new Circle();

            Shape rectangle = new Rectangle();

 

            // Call methods

            circle.Display();

            circle.Draw();

 

            rectangle.Display();

            rectangle.Draw();

        }

    }

}

 

 

6. What is the difference between an abstract class and an interface in C#?

Answer:

Abstract Class: Can have both abstract and non-abstract methods, properties, and fields. It is used when you want to provide some common functionality for derived classes.

Interface: Only contains declarations of methods, properties, events, or indexers. It is used to achieve full abstraction and multiple inheritance. All members are abstract by default in interfaces.

7. Explain the concept of boxing and unboxing in C#.

Answer:

Boxing: Converting a value type (e.g., int) to an object type or any interface type that it implements. It’s a process of wrapping a value type inside an object.

Unboxing: Extracting the value type from the object. This is the reverse of boxing.

8. What is the purpose of the using statement in C#?

Answer: The using statement in C# is used to ensure that resources are disposed of once they go out of scope. It is typically used for managing unmanaged resources such as file handles, database connections, etc., and is helpful for automatic disposal of objects that implement the IDisposable interface.

9. What is LINQ in C#?

Answer: LINQ (Language Integrated Query) is a set of extensions in C# that provides a querying syntax for querying data sources like collections, databases, XML, etc. It allows you to write queries directly in C# using a SQL-like syntax.

10. What is the difference between == and .Equals() in C#?

Answer:

== is a reference equality operator, and its behavior varies depending on the type. For reference types, it checks if the two references point to the same object. For value types, it checks if the values are equal.

.Equals() is used to determine if two objects have the same value, and it can be overridden in classes to provide custom equality comparison.

11. What are async and await keywords in C#?

Answer: async and await are used for asynchronous programming in C#. The async keyword is used to declare a method that performs an asynchronous operation, and await is used to suspend the execution of an async method until the awaited task completes. This helps prevent blocking the main thread.

12. What is the purpose of the Nullable<T> in C#?

Answer: Nullable<T> is a structure that allows value types to represent null values, which is typically used for database applications where fields may contain null values. For example, Nullable<int> or int? allows an integer to have a null value.

13. Explain the is and as operators in C#.

Answer:

is Operator: Checks if an object is of a particular type and returns a boolean value.

as Operator: Attempts to cast an object to a specified type. If the cast is not successful, it returns null instead of throwing an exception.

14. What is dependency injection, and why is it useful?

Answer: Dependency injection is a design pattern that allows for the injection of dependencies into a class rather than having the class create its own dependencies. This helps to decouple components, making code more modular, testable, and maintainable.

15. What is the difference between Array and ArrayList in C#?

Answer:

Array: Fixed size and strongly typed; it can only store elements of a specific type.

ArrayList: Resizable array and can store elements of different types as it stores objects, not specific types.

 

There are four types of access modifiers:

 

· Private: The access level of a private modifier is only within the class. It cannot be accessed from outside the class.

· Default: The access level of a default modifier is only within the package. It cannot be accessed from outside the package. If you do not specify any access level, it will be the default.

· Protected: The access level of a protected modifier is within the package and outside the package through child class. If you do not make the child class, it cannot be accessed from outside the package.

· Public: The access level of a public modifier is everywhere. It can be accessed from within the class, outside the class, within the package and outside the package.

 

Jagged Array-- A jagged array is an array of arrays, where each element in the main array can have a different length. In simpler terms, a jagged array is an array whose elements are themselves arrays. These inner arrays can have different lengths. Can also be mixed with multidimensional arrays. The number of rows will be fixed at the declaration time but can vary the number of columns.

 

            int[][] jagged = new int[3][];

            jagged[0] = new int[2];

            jagged[0][0] = 1;

            jagged[1] = new int[1];

            jagged[2] = new int[3] { 3, 4, 5 };

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

            {

                int[] innerArray = jagged[i];

                for (int j = 0; j < innerArray.Length; j++)

                {

                    Console.Write(innerArray[j] + " ");

                }

                Console.WriteLine();

            }

XML Serialisation

XML- extensible markup language

----Serialization is the process of converting an object into a stream of bytes.

 

namespace jaggedarray

{

    public class Person

    {

        public string name;

        public string location;

        public int age;

    }

    internal class Program

    {

        static void Main(string[] args)

        {

 

            Person p = new Person();

            p.name = "Reshma";

            p.location = "Chengannur";

            p.age = 26;

            XmlSerializer x = new XmlSerializer(p.GetType());

            x.Serialize(Console.Out, p);

 

        }

    }

}

Delegate-------A delegate is an object which refers to a method or you can say it is a reference type variable that can hold a reference to the methods. It provides a way which tells which method is to be called when an event is triggered.

Syntax ---[modifier] delegate [return_type] [delegate_name] ([parameter_list]);

namespace @delegate

{

    public delegate double mydelegate(int a, int b);

    internal class Program

    {

        static double myfun(int x, int y)

        {

            return x * y;

        }

        static void Main(string[] args)

        {

            mydelegate del = new mydelegate(myfun);

            Console.WriteLine("Please enter two numbers");

            int P = Convert.ToInt32(Console.ReadLine());

            int Q = Convert.ToInt32(Console.ReadLine());

            double res = del(P, Q);

            Console.WriteLine("Result:" + res);

        }

    }

}

 

Break----The break statement can also be used to jump out of a loop.

internal class Program

{

    static void Main(string[] args)

    {

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

        {

            if (i == 4)

            {

                break;

            }

            Console.WriteLine(i);

        }

    }

}

Continue--- The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop

internal class Program

 {

     static void Main(string[] args)

     {

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

         {

             if (i == 4)

             {

                 continue;

             }

             Console.WriteLine(i);

         }

o/p—12356789

  internal class Program

  {

      static int sum(int c,int d)

      {

          return c + d;

      }

      static int subt(int c,int d)

      {

          return (c - d);

      }

      static int multi(int c, int d)

      {

          return c * d;

      }

      static int div(int c, int d) {

          return c / d;

      }

 

      static void Main(string[] args)

      {

          Console.WriteLine("Enter two numbers");

          int a = Convert.ToInt32(Console.ReadLine());

          int b = Convert.ToInt32(Console.ReadLine());

          Console.WriteLine("Enter a sign");

          String c=Console.ReadLine();

          switch (c)

          {

              case "+":

                    

          Console.WriteLine("Sum is " + sum(a, b));

          break;

              case "-":

                  Console.WriteLine("Differencs is " + subt(a, b));

                  break;

                  case "*":

                  Console.WriteLine("Product is " + multi(a, b));

                  break;

                  case "/":

                  Console.WriteLine("Division ans is " + div(a, b));

                  break;

                  default:

                  Console.WriteLine("INvalid Operator");

                  break;

 

 

 

C# - What is OOP?

 OOP stands for Object-Oriented Programming.

 Procedural programming is about writing procedures or methods that perform operations on the data, while object-oriented programming is about creating objects that contain both data and methods. Object-oriented programming has several advantages over procedural programming:

 OOP is faster and easier to execute OOP provides a clear structure for the programs

OOP is faster and easier to execute OOP provides a clear structure for the programs

 

THE FOLLOWINGS ARE THE FEATURES OF OOPS:

1.Class

2.Objects

3.Encapsulation

4.Abstraction

5.Inheritance

6.polymophism

Class -class is a group of similar objects.Class is a way to bind data describing an entity and assossiated functions together. Object –object is an identifier entity that have some characteristics and behavior. Abstraction-It is a concept of simplifying a real world object into its essential features without including background details.

Encapsulation-Wrapping up of data into single unit is known as encapsulation. Inheritance –It is a property of inheriting properties of one class to another.

 Polymorphism-The word polymorphism means having many forms. In object-oriented programming paradigm, polymorphism is often expressed as 'one interface, multiple functions'.

Polymorphism can be static or dynamic.

In static polymorphism, the response to a function is determined at the compile time.

In dynamic polymorphism, it is decided at run-time.

POLYMORPHISM-"Poly" means many and "morph" means forms. Polymorphism provides the ability to a class to have multiple implementations with the same name.

Class Syntax Classname objectname= new classname(); Eg: Program p= new Program();

 

Encapsulation(Data Hiding)

Encapsulation is an object-oriented programming concept that allows programmers to wrap data and code snippets inside an enclosure. By using the encapsulation program, you can hide the members of one class from another class. It’s like encircling a logical item within a package. It allows only relevant information available and visible outside and that too only to specific members.Encapsulation is implemented by using access specifiers.

Access Specifier is used for defining the visibility and accessibility of the class member in C#.

C# contains the following access specifiers

• Public

• Private

• Protected

• Internal

Public: The public keyword allows its members to be visible from anywhere inside the project. This access specifier has the least visibility restriction.

Private: The private members can only be accessed by the member within the same class. This has one of the most restricted visibility.

 Protected: Protected accessibility allows the member to be accessed from within the class and from another class that inherits this class.

 Internal: Internal provides accessibility from within the project.

Private

namespace Encapsulation__private

{

     class Program

    {

        private string model;

 

        static void Main(string[] args)

        {

            Program p = new Program();

            p.model = "BMW";

            Console.WriteLine(p.model);

        }

    }

}

 

Public

namespace encap_public

{

    class Car

 

    {

 

        public string model = "Mustang";

 

    }

    internal class Program

    {

        static void Main(string[] args)

        {

            Car myObj = new Car();

 

            Console.WriteLine(myObj.model);

        }

    }

}

Protected

namespace encap_protected

{

    class X

    {

 

 

 

        // Member x declared

 

        // as protected

 

        protected int x;

 

 

 

        public X()

 

        {

 

            x = 10;

 

        }

 

    }

 

    class Y : X

    {

 

 

        public int getX()

 

        {

 

            return x;

 

        }

 

    }

    internal class Program

    {

        static void Main(string[] args)

        {

           

 

            Y obj2 = new Y();

 

 

 

            // Displaying the value of x

           

            Console.WriteLine("Value of x is : {0}", obj2.getX());

        }

    }

}

Internal

namespace encP_INTERNAL

{

    class access

 

    {

 

        // String Variable declared as internal

 

        internal string name;

 

        public void print()

 

        {

 

            Console.WriteLine("\nMy name is " + name);

 

        }

 

    }

 

 

    internal class Program

    {

        static void Main(string[] args)

        {

            access ac = new access();

 

            Console.Write("Enter your name:\t");

 

            // Accepting value in internal variable

 

            ac.name = Console.ReadLine();

 

            ac.print();

 

            Console.ReadLine();

        }

    }

}

Polymorphism

POLYMORPHISM-"Poly" means many and "morph" means forms.

Polymorphism provides the ability to a class to have multiple implementations with the same name. Types of Polymorphism

There are two types of polymorphism in C#:

Static / Compile Time Polymorphism.(function overloading)

Dynamic / Runtime Polymorphism.(function overriding)

Function Overloading(Method Overloading)

Method overloading is an example of Static Polymorphism. In overloading, the method / function has a same name but different signatures.

namespace overloading

{

    public class TestData

 

    {

 

        public int Add(int a, int b, int c)

 

        {

 

            return a + b + c;

 

        }

 

        public int Add(int a, int b)

 

        {

 

            return a + b;

 

        }

 

    }

    internal class Program

    {

        static void Main(string[] args)

        {

            TestData dataClass = new TestData();

 

            int add2 = dataClass.Add(45, 34, 67);

 

            int add1 = dataClass.Add(23, 34);

 

            Console.WriteLine(add2);

 

            Console.WriteLine(add1);

        }

    }

}

 

Method overriding can be done using inheritance. With method overriding it is possible for the base class and derived class to have the same method name and same something.

namespace overriding

{

    public class Drawing

 

    {

 

        public virtual double Area()

 

        {

 

            return 0;

 

        }

 

    }

 

 

 

    public class Circle : Drawing

 

    {

 

        public double Radius { get; set; }

 

        public Circle()

 

        {

 

            Radius = 5;

 

        }

 

        public override double Area()

 

        {

 

            return (3.14) * Math.Pow(Radius, 2);

 

        }

 

    }

    public class Square : Drawing

 

    {

 

        public double Length { get; set; }

 

        public Square()

 

        {

 

            Length = 6;

 

        }

 

        public override double Area()

 

        {

 

            return Math.Pow(Length, 2);

 

        }

 

    }

 

 

 

    public class Rectangle : Drawing

 

    {

 

        public double Height { get; set; }

 

        public double Width { get; set; }

 

        public Rectangle()

 

        {

 

            Height = 5.3;

 

            Width = 3.4;

 

        }

        public override double Area()

 

        {

 

            return Height * Width;

 

        }

 

    }

    internal class Program

        {

            static void Main(string[] args)

            {

                Drawing obj1 = new Circle();

 

                Console.WriteLine("Area :" + obj1.Area());

 

 

 

                Drawing obj2 = new Square();

 

                Console.WriteLine("Area :" + obj2.Area());

 

 

 

                Drawing obj3 = new Rectangle();

 

                Console.WriteLine("Area :" + obj3.Area());

            }

        }

    }

 

 

Interface

In C#, an interface is a fundamental concept defining a contract or a set of rules a class must adhere to. It specifies a list of methods, properties, events, or indexers a class implementing the interface must provide. Interfaces allow you to define a common set of functionality that multiple classes can share, promoting code reusability and ensuring a consistent structure for related classes.

An interface is also a user-defined data type.

 

 

namespace @interface

{

    interface ITestInterface1

    {

        void Add(int num1, int num2);

    }

    interface ITestInterface2 : ITestInterface1

    {

        void Sub(int num1, int num2);

    }

    public class ImplementationClass1 : ITestInterface1

    {

        //Implement only the Add method

        public void Add(int num1, int num2)

        {

            Console.WriteLine($"Sum of {num1} and {num2} is {num1 + num2}");

        }

    }

    public class ImplementationClass2 : ITestInterface2

    {

        //Implement Both Add and Sub method

        public void Add(int num1, int num2)

        {

            Console.WriteLine($"Sum of {num1} and {num2} is {num1 + num2}");

        }

        

public void Sub(int num1, int num2)

        {

            Console.WriteLine($"Difference of {num1} and {num2} is {num1 - num2}");

        }

    }

    internal class Program

    {

 

        static void Main(string[] args)

        {

            ImplementationClass1 obj1 = new ImplementationClass1();

            //Using obj1 we can only call Add method

            obj1.Add(10, 20);

            //We cannot call Sub method

            //obj1.Sub(100, 20);

            ImplementationClass2 obj2 = new ImplementationClass2();

            //Using obj2 we can call both Add and Sub method

            obj2.Add(10, 20);

            obj2.Sub(100, 20);

        }

    }

}

namespace @interface

{

    interface ITestInterface1

    {

        void Add(int num1, int num2);

    }

    interface ITestInterface2 : ITestInterface1

    {

        void Sub(int num1, int num2);

    }

    public class ImplementationClass1

    {

        //Implement only the Add method

        public void Add(int num1, int num2)

        {

            Console.WriteLine($"Sum of {num1} and {num2} is {num1 + num2}");

        }

    }

    public class ImplementationClass2 : ITestInterface2,ITestInterface1

    {

        //Implement Both Add and Sub method

        public void Add(int num1, int num2)

        {

            Console.WriteLine($"Sum of {num1} and {num2} is {num1 + num2}");

        }

        

public void Sub(int num1, int num2)

        {

            Console.WriteLine($"Difference of {num1} and {num2} is {num1 - num2}");

        }

    }

    internal class Program

    {

 

        static void Main(string[] args)

        {

            ImplementationClass1 obj1 = new ImplementationClass1();

            //Using obj1 we can only call Add method

            obj1.Add(10, 20);

            //We cannot call Sub method

            //obj1.Sub(100, 20);

            ImplementationClass2 obj2 = new ImplementationClass2();

            //Using obj2 we can call both Add and Sub method

            obj2.Add(10, 20);

            obj2.Sub(100, 20);

        }

    }

}

 Tokens

Token refers to a fundamental unit of code that the compiler uses to understand the structure and meaning of the source code. Here are some examples of tokens in C#:


1. Keywords: These are reserved words with predefined meanings in the C# language, such as class, if, for, while, int, etc.


2. Identifiers: These are names given to entities in a program, such as variables, functions, classes, etc. Identifiers can include letters, digits, and underscores, but must follow certain naming conventions and cannot be a C# keyword.


3. Literals: These are constant values explicitly specified in the code. For example, 42 is an integer literal, "Hello" is a string literal, true is a Boolean literal, etc.


4. Operators: These are symbols used to perform operations on variables or values, such as +, -,

*, /, &&, ||, ==, =, etc.


5. Punctuation Marks: These include symbols like parentheses (), braces {}, square brackets [], semicolons; commas, periods., etc., used for grouping, separating, or terminating code elements.


OPERATORS

The followings are the operators in c#:


1. Arithmetic operators


2. Assignment operators


3. Logical operators


4. Conditional operators


5. Relational operators


6. Increment operator


7. Decrement operators

 

Arithmetic operators


+ - * / % using System;

using System. Collections. Generic; using System.Linq;

using System.Text;


using System.Threading.Tasks;




namespace arithmetic


{


internal class Program


{


static void Main(string[] args)


{


int a = 20; int b = 10;

Console. WriteLine("SUM=" + (a + b)); Console. WriteLine("difference=" + (a - b)); Console. WriteLine("product=" + (a * b)); Console. WriteLine("division=" + (a / b)); Console. WriteLine("modulus=" + (a % b));

 




}


}


}


======================================================================




Assignment operators


+= -= *= /= %=


using System;


using System.Collections.Generic; using System.Linq;

using System.Text;


using System.Threading.Tasks;




namespace assignment operator


{


internal class Program


{


static void Main(string[] args)


{


int a = 20;

 

a += 3;


Console. WriteLine(a); a -= 2;

Console. WriteLine(a); a *= 3;

Console. WriteLine(a); a /= 4;

Console. WriteLine(a); a %= 2;

Console. WriteLine(a);


}


}


}


======================================================================




Conditional operators




Ø Syntax: (condition)? True: false; Console. WriteLine("Enter 2 numbers:");



Int a=Convert.ToInt32(Console.ReadLine()); int b=Convert.ToInt32(Console.ReadLine());

 

int max = (a > b) ? a : b; Console. WriteLine("big= “+max);


======================================================================




Logical operators


( AND &&, OR || , NOT EQUALTO !=)




using System;


using System.Collections.Generic; using System.Linq;

using System.Text;


using System.Threading.Tasks;




namespace logical operators


{


internal class Program


{


static void Main(string[] args)


{




Console. WriteLine("Enter 4 numbers");




int a = Convert.ToInt32(Console.ReadLine());

 

int b = Convert.ToInt32(Console.ReadLine());




int c = Convert.ToInt32(Console.ReadLine()); int d = Convert.ToInt32(Console.ReadLine());







if ((a > b) && (a > c) && (a > d))




Console. WriteLine("big= " + a);




else if ((b > a) && (b > c) && (b > d))




Console. WriteLine("big= " + b);




else if (c > d)




Console. WriteLine("big= " + c);




else

 

Console. WriteLine("big=" + d);


}


}}


======================================================================




Logical OR


Console. WriteLine("Enter a character");


char a = Convert.ToChar(Console.ReadLine());’ if((a=='a' ) || (a=='e') || (a=='i') || (a=='o') ||(a=='u'))

{


Console. WriteLine("Vowels");


}


else { Console. WriteLine("Not a vowel"); } Not equal

Console. WriteLine("Enter a number");




int a = Convert.ToInt32(Console.ReadLine()); if (a % 2 == 0)

Console. WriteLine("even"); if (a % 2 != 0)

Console. WriteLine("ODD");


======================================================================

 

Increment/Decrement Operators






Console. WriteLine("Enter a number");


int a = Convert.ToInt32(Console.ReadLine()); a++; //increment

Console. WriteLine(a); a--; //decrement

Console. WriteLine(a);



C# Type casting


Type casting is when you assign a value of one data type to another type In C3 ,ther are two types of casting


a) Implicit casting (automatically): converting a smaller type to a larger type size; char->int->long->float->double


b) Explicit casting (manually) :-> converting a larger type to smaller size type double->float->long->int->char


Type conversion method


It is also possible to convert data types explicitly by using built-in methods ,such as convert to boolean ,convert to double ,convert to

 

string,convert to int 32,convert to int64.


 

What is an IL?


(IL)Intermediate Language is also known as MSIL (Microsoft Intermediate Language) or CIL

(Common Intermediate Language). All .NET source code is compiled to IL.

This IL is then

converted to machine code at the point where the software is installed, or at run-time by a Just-InTime (JIT) compiler.


What is a CLR?


Full form of CLR is Common Language Runtime and it forms the heart of the .NET framework.All Languages have runtime and its the responsibility of the runtime to take care of the code execution of the program.For example VC++ has MSCRT40.DLL,VB6 has MSVBVM60.DLL , Java has Java Virtual Machine etc. Similarly .NET has CLR.Following are the responsibilities of CLR

 √ Garbage Collection :- CLR automatically manages memory thus eliminating memory leaks. When objects are not referred GC automatically releases those memory thus providing efficient memory management.

 √ Code Access Security :- CAS grants rights to program depending on the security configuration of the machine.Example the program has rights to edit or create a new file but the security configuration of machine does not allow the program to delete a file.CAS will take care that the code runs under the environment of machines security configuration.

√ Code Verification :- This ensures proper code execution and type safety while the code runs.It prevents the source code to perform illegal operations such as accessing invalid memory locations etc.

√ IL( Intermediate language )-to-native translators and optimizer’s :- CLR uses JIT and compiles the IL code to machine code and then executes. CLR also determines, depending on the platform, what is the optimized way of running the IL code.

 

What is a CTS?


In order that two languages communicate smoothly CLR has CTS (Common Type System).Example in VB you have “Integer” and in C++ you have “long” these datatypes are not compatible so the interfacing between them is very complicated. In order that two different languages can communicate Microsoft introduced the Common Type System. So “Integer” datatype in VB6 and “int” datatype in C++ will convert it to System.int32 which is a datatype of CTS.CLS which is covered in the coming question is a subset of CTS.


What is a CLS(Common Language Specification)?

This is a subset of the CTS which all .NET languages are expected to support.It was always a dream of microsoft to unite all different languages in to one umbrella and CLS is one step towards that.Microsoft has defined CLS which are nothing but guidelines that language to follow so that it can communicate with other .NET languages in a seamless manner














If-else-if

using System;

 

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;


namespace ConsoleApplicationifelseif

{

class Program

{

static void Main(string[] args)

{

Console.WriteLine("Enter a number");

int a = Convert.ToInt32(Console.ReadLine()); if (a == 1)

Console.WriteLine("Sunday"); else if (a == 2)

Console.WriteLine("Monday"); else if (a == 3)

Console.WriteLine("Tuesday"); else if (a == 4)

Console.WriteLine("Wednesday"); else if (a == 5)

Console.WriteLine("Thursday"); else if (a == 6)

Console.WriteLine("Friday"); else

Console.WriteLine("Invalid"); Console.ReadKey();

}

}

 

}


Switch case

using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;


namespace ConsoleApplicationswitchcase

{

class Program

{

static void Main(string[] args)

{

Console.WriteLine("enter a number");

int a = Convert.ToInt32(Console.ReadLine()); switch(a)

{

case 1:

Console.WriteLine("Sunday"); break;

case 2:

Console.WriteLine("monday"); break;

case 3:

Console.WriteLine("Tuesday"); break;

case 4:

Console.WriteLine("Wednesday");

 

break; case 5:

Console.WriteLine("Thersday"); break;

case 6:

Console.WriteLine("friday"); break;

case 7:

Console.WriteLine("saturday"); break;

default:

Console.WriteLine("invalid"); break;

}

Console.ReadKey();

}

}

}


Switch case operator

using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;


namespace ConsoleApplicationoperator

{

class Program

{

 

static void Main(string[] args)

{

Console.WriteLine("Enter two number");

int a = Convert.ToInt32(Console.ReadLine()); int b = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Enter your choice");

Char c = Convert.ToChar(Console.ReadLine()); switch(c)

{

case '+':

Console.WriteLine("sum =" + (a + b)); break;

case '-':

Console.WriteLine("difference =" + (a - b)); break;

case '*':

Console.WriteLine("Product =" + (a * b)); break;

case '/':

Console.WriteLine("division =" + (a /b)); break;

default:

Console.WriteLine("invalid"); break;

}

Console.ReadKey();

}

}

}

 

Biggest of 3 numbers


using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;


namespace ConsoleApplicationbiggest

{

class Program

{

static void Main(string[] args)

{

Console.WriteLine("Enter 3 numbers :");

int a = Convert.ToInt32(Console.ReadLine()); int b = Convert.ToInt32(Console.ReadLine()); int c = Convert.ToInt32(Console.ReadLine()); if((a>b) && (a>c))

{

Console.WriteLine(a + " is largest");

}

else if ((b> a) && (b > c))

{

Console.WriteLine(b + " is largest");

}

else

Console.WriteLine(c + " is largest");

 

Console.ReadKey();

}

}

}


OR


using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;


namespace ConsoleApplicationvvowels

{

class Program

{

static void Main(string[] args)

{

Console.WriteLine("Enter letter");

char c =Convert.ToChar(Console.ReadLine()); if(c=='a'||

c=='A'||c=='e'||c=='E'||c=='i'||c=='I'||c=='o'||c=='O'||c=='u'||c=='U')

{

Console.WriteLine("The character is Vowel");

}

else

{

 

Console.WriteLine("The character is not Vowel");

}

Console.ReadKey();

}

}

}


While loop using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;


namespace ConsoleApplicationWhileloop

{

class Program

{

static void Main(string[] args)

{

Console.WriteLine("Enter the limit of loop"); int iNo = Convert.ToInt32(Console.ReadLine()); int i = 1;

Console.WriteLine("The Numbers are"); while (i<= iNo)

 

{

Console.WriteLine(i); i++;

}

Console.ReadKey();

}

}

}



using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;


namespace ConsoleApplicationmultiplicationtable

{

class Program

{

static void Main(string[] args)

{

Console.WriteLine("which multiplication table you want?"); int imul = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Enter limit you want print");

int iwp = Convert.ToInt32(Console.ReadLine()); int i = 1;

while(i<=iwp)

 

{

Console.WriteLine(i + "*" + imul + "=" + i * imul); i++;

}

Console.ReadKey();

}

}

}



do-while using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;


namespace ConsoleApplicationmultiplicationtable

{

class Program

{

static void Main(string[] args)

{

Console.WriteLine("which multiplication table you want?"); int imul = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Enter limit you want print");

 

int iwp = Convert.ToInt32(Console.ReadLine()); int i = 1;

do

{

Console.WriteLine(i + "*" + imul + "=" + i * imul); i++;

} while (i <= iwp);


Console.ReadKey();

}

}

}



for-loop using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;


namespace ConsoleApplicationmultiplicationtable

{

class Program

{

static void Main(string[] args)

 

{

Console.WriteLine("which multiplication table you want?"); int imul = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Enter limit you want print");

int iwp = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Multiplication table :");


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

{


Console.WriteLine(i + "*" + imul + "=" + i * imul);



}

Console.ReadKey();

}

}

}


using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;


namespace ConsoleApplicationmultiplicationtable

{

class Program

 

{

static void Main(string[] args)

{

Console.WriteLine("which multiplication table you want?"); int imul = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Enter limit you want print");

int iwp = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Multiplication table :");


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

{


// Console.WriteLine(i + "*" + imul + "=" + i * imul); Console.WriteLine("{0} * {1} ={2}", i,imul,i*imul);



}

Console.ReadKey();

}

}

}

o/p

which multiplication table you want? 4

Enter limit you want print 10

Multiplication table : 1 * 4 =4

 

2 * 4 =8

3 * 4 =12

4 * 4 =16

5 * 4 =20

6 * 4 =24

7 * 4 =28

8 * 4 =32

9 * 4 =36

10 * 4 =40

febinocii series using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;


namespace ConsoleApplicationfebinocii

{

class Program

{

static void Main(string[] args)

{

Console.WriteLine("Enter the febinocii limit"); int ifebi = Convert.ToInt32(Console.ReadLine()); int first = 0, second = 1, next; Console.WriteLine("the febinocii series are");

 

Console.Write(first + " " + second + " "); for(int i=2;i<ifebi;i++)

{

next = first + second; Console.Write(next + " "); first = second;

second = next;

}

Console.ReadKey();

}

}

}



sum of digits using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;


namespace ConsoleApplicationsum

{

class Program

{

static void Main(string[] args)

{

Console.WriteLine("Enter the starting number");

 

int isNo = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Enter the Last number");

int iLNo = Convert.ToInt32(Console.ReadLine()); int sum = 0;

for (int i = isNo; i <=iLNo;i++)

{

if(isNo==iLNo)

{

sum =isNo;

}

sum += i;

}

Console.WriteLine("Sum =" + sum); Console.ReadKey();

}

}

}



array read write and using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;


namespace ConsoleApplicationForeachreadandprint

{

 

class Program

{

static void Main(string[] args)

{

Console.WriteLine("Enter the number of element"); int size = int.Parse(Console.ReadLine());

int[] numbers = new int[size]; Console.WriteLine("Enter the elements"); for(int i=0;i<size;i++)

{

Console.Write("Element {"+i+" 1 }:"); numbers[i] = int.Parse(Console.ReadLine());


}

Console.WriteLine("Array elements are :"); foreach(int num in numbers)

{

Console.WriteLine(num);

}

Console.ReadKey();

}

}

}



conditional operator using System;

 

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;


namespace ConsoleApplicationconsitionaloperator

{

class Program

{

static void Main(string[] args)

{

Console.WriteLine("Enter 2 numbers");

int a = Convert.ToInt32(Console.ReadLine()); int b = Convert.ToInt32(Console.ReadLine()); int max = (a > b) ? a : b; Console.WriteLine("Big =" + max); Console.ReadKey();

}

}

}


Date and Time using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

 

using System.Threading.Tasks;


namespace ConsoleApplicationDateandtime

{

class Program

{

static void Main(string[] args)

{

Console.WriteLine("Date ="+ DateTime.Now); Console.WriteLine("Date =" + DateTime.Now.ToString()); Console.WriteLine("Date =" +

DateTime.Now.ToLongDateString()); Console.WriteLine("Date =" + DateTime.Now.ToShortDateString()); Console.WriteLine("Date =" + DateTime.Now.ToLongTimeString()); Console.WriteLine("Date =" + DateTime.Now.ToShortTimeString());

Console.WriteLine("Date =" + DateTime.Now.Year); Console.WriteLine("Date =" + DateTime.Now.Month); Console.WriteLine("Date =" + DateTime.Now.Day); Console.WriteLine("Date =" + DateTime.Now.Hour); Console.WriteLine("Date =" + DateTime.Now.Minute); Console.WriteLine("Date =" + DateTime.Now.Second); Console.WriteLine("Date =" + DateTime.Now.Millisecond); Console.ReadKey();

}

}

 

}

string properties using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;


namespace ConsoleApplicationstringproperties

{

class Program

{

static void Main(string[] args)

{

string str = "TrivandrumKollam"; Console.WriteLine(str); Console.WriteLine("length =" + str.Length); Console.WriteLine(str.Substring(5)); Console.WriteLine(str.Substring(3, 7));

Console.WriteLine(str.Remove(3, 4)); Console.WriteLine(str.Replace("i", "z")); Console.WriteLine(str.PadLeft(40, '*')); Console.WriteLine(str.PadRight(40, '*')); Console.ReadKey();

}

}

}

 

o/p TrivandrumKollam length =16 ndrumKollam vandrum TrirumKollam TrzvandrumKollam

************************TrivandrumKollam TrivandrumKollam************************



math properties using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;


namespace ConsoleApplicationmathprop

{

class Program

{

static void Main(string[] args)

{

Console.WriteLine(Math.PI);

 

Console.WriteLine(Math.Max(5,10)); Console.WriteLine(Math.Min(5, 10)); Console.WriteLine(Math.Sqrt(64)); Console.WriteLine(Math.Abs(-4.7)); Console.WriteLine(Math.Round(9.99)); Console.ReadKey();

}

}

}


o/p 3.14159265358979

10

5

8

4.7

10



LINQ(Language integrated query)


Array methods ,such as min,max, and sum can be found in the system.Linq namespace,manage the query

using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace ConsoleApplicationLinq

{

class Program

{

static void Main(string[] args)

{

int[] mynumber = { 5, 1, 8, 9 }; Console.WriteLine("Largest number is"); Console.WriteLine(mynumber.Max()); Console.WriteLine("smallest number is"); Console.WriteLine(mynumber.Min()); Console.WriteLine("sum of number is"); Console.WriteLine(mynumber.Sum()); Console.ReadKey();

}

}

}



o/p

Largest number is 9

smallest number is 1

sum of number is 23

 

sort

using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;


namespace ConsoleApplicationSort

{

class Program

{

static void Main(string[] args)

{

int[] a = new int[5]; Console.WriteLine("Enter five numbers"); for (int i = 0; i < 5; i++)

{

a[i] = Convert.ToInt32(Console.ReadLine());

}

Console.WriteLine("The number of ascending order"); Array.Sort(a);

for(int i=0;i<5;i++)

{

Console.WriteLine(a[i]);

}

Console.ReadKey();

}

 

}

}


Enter five numbers 5

2

6

9

1

The number of ascending order 1

2

5

6

9


descending order using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;


namespace ConsoleApplicationSort

{

class Program

 

{

static void Main(string[] args)

{

int[] a = new int[5]; Console.WriteLine("Enter five numbers"); for (int i = 0; i < 5; i++)

{

a[i] = Convert.ToInt32(Console.ReadLine());

}

Console.WriteLine("The number of descending order"); Array.Sort(a);

Array.Reverse(a); for(int i=0;i<5;i++)

{

Console.WriteLine(a[i]);

}

Console.ReadKey();

}

}

}



Enter five numbers 12

4

20

18

10

 

The number of descending order 20

18

12

10

4



Reverse for reverse the letter or number sort for sort the ascending order



MULTI THREADING


using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks; using System.Threading;

namespace ConsoleApplicationThread


{

class Program

{

static void funcloop()

{

for(int i=11;i<20;i++)

 

{

Console.WriteLine(i);

}

}

static void Main(string[] args)

{

ThreadStart childthread = new ThreadStart(funcloop); Thread obj = new Thread(childthread);

obj.Start();

{

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

{

Console.WriteLine(i);

}

}

Console.ReadKey();

}

}

}


o/p 0

1

2

3

11

12

13

 

14

15

16

17

18

19

4

5

6

7

8

9


Output can be changed because of the 2 for loop working at the same time,so we can't predict the output, 2 loop are clashed


Thread sleep



using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks; using System.Threading;


namespace ConsoleApplicationthreadsleep

{

 

class Program

{

static void function()

{

for(int i=11;i<20;i++)

{

Console.WriteLine(i);

}

}

static void Main(string[] args)

{

ThreadStart childhead = new ThreadStart(function); Thread obj = new Thread(childhead);

obj.Start(); Thread.Sleep(2000); for(int i=0;i<10;i++)

{

Console.WriteLine(i);

}

Console.ReadKey();

}

}

}

o/p


11

12

13

 

14

15

16

17

18

19

After 200 ms

0

1

2

3

4

5

6

7

8

9

XML Serialization

XML ->extensible markup language


using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks; using System.Xml.Serialization;


namespace ConsoleApplicationxmlserialaization

 

{

public class person

{

public string name; public string location; public int age;

}


class Program

{


static void Main(string[] args)

{

person p = new person(); p.name = "Anzi"; p.location = "Kollam"; p.age = 32;

XmlSerializer x = new XmlSerializer(p.GetType()); x.Serialize(Console.Out, p);

Console.ReadKey();

}

}

}


o/p

<?xml version="1.0" encoding="DOS-720"?>

 

<person

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">

<name>Anzi</name>

<location>Kollam</location>

<age>32</age>

</person>


Jagged Array using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;


namespace ConsoleApplicationjaggedarray

{

class Program

{

static void Main(string[] args)

{

//Declare jagged array

int[][] jaggedarray = new int[3][];

//initialoze the elements of jagged array jaggedarray[0] = new int[] { 1, 2, 3 };

jaggedarray[1] = new int[] { 4, 5, 6, 7 };

 

jaggedarray[2] = new int[] { 8, 9 };

//Accesing elements in the jagged array for(int i=0;i<jaggedarray.Length;i++)

{

Console.WriteLine(); Console.Write("Elements[{0}]", i); for(int j=0;j<jaggedarray[i].Length;j++)

{

Console.Write("{0}", jaggedarray[i][j]);

}

}

Console.ReadKey();


}

}

}




o/p


Elements[0]123 Elements[1]4567 Elements[2]89



C# methods /Functions

 

A method is a block of code which only runs when it is called

.you can pass data ,known as parameters into a method.Methods are used to perform certain actions and they are also known as function ,reusable

using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;


namespace ConsoleApplicationfunctions

{

class Program

{

static void mymethod()

{

Console.WriteLine("i just not executed");

}

static void Main(string[] args)

{

mymethod(); mymethod(); mymethod(); Console.ReadKey();

}


}

 

}


o/p

i just not executed i just not executed i just not executed














OOPS

1.Class 2.object

3.Encapsulation 4.Abstraction 4.Inheritance 5.polymorphism

 

1. class


Class is a blueprint of a program.class is a group of similar objects .class is a key to bind data describing on entity and associated functions together.the keyword class is used to create a class.


Syntax

Class classname

{

Variable declaration; Function declarations;

}





2. Object

Object is an identifier entity that have some characteristics and behaviour


Syntax

Classname objectname=new classneme(); Example

 

using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;


namespace ConsoleApplicationoops

{

public class oopsexamples

{

public string color = "Red";

}

class Program

{

static void Main(string[] args)

{

oopsexamples myovj = new oopsexamples(); Console.WriteLine(myovj.color); Console.ReadKey();

}

}

}


o/p

 

Red Example

using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;


namespace ConsoleApplicationoops

{


class Program

{

int a, b, c;

static void Main(string[] args)

{

Program myovj = new Program(); Console.WriteLine("Enter two numbers"); myovj.a = Convert.ToInt32(Console.ReadLine()); myovj.b = Convert.ToInt32(Console.ReadLine()); myovj.c = myovj.a + myovj.b; Console.WriteLine("sum ="+myovj.c); Console.ReadKey();

 

}

}

}


o/p

Enter two numbers 3

6

sum =9








3. INHERITANCE

It is the property of inheriting the properties of one class to another ;


Syntax

Class derivedclass:baseclass

{

//methods and fields

}

The derived class is is called child or sub class

 

The base class is called parent class or main class The main advantages is reusability;

Types of inheritance


a) Single inheritance

A derived class that inherit from only one base class



A-> Super class

B->Sub class




Example using System;

using System.Collections.Generic;

 

using System.Linq; using System.Text;

using System.Threading.Tasks;


namespace ConsoleApplicationinheritence

{

//super class class Animal

{

public void eat()

{

Console.WriteLine("This animal eats food.");

}

}

// Subclass

class Dog : Animal

{

public void bark()

{

Console.WriteLine("The dog barks.");

}

}

class Program

{

static void Main(string[] args)

 

{

Dog labrador = new Dog();

labrador.eat(); // Inherited method from Animal labrador.bark(); // Method from Dog Console.ReadKey();

}

}

}

o/p

This animal eats food. The dog barks.


b) Hierarchical inheritance


A parent class and multiple child class is .


Hierarchical inheritance is a type of inheritance in Java where a single parent class (base class) is extended by multiple child classes (subclasses). Each child class inherits the properties and methods of the parent class independently, allowing for code reuse and logical organization.

Key Features

Single Parent, Multiple Children: One parent class is shared among multiple child classes.

Code Reusability: Common functionality is defined in the parent class, reducing redundancy.

Independent Behavior: Each child class can have its own unique methods and properties in addition to the inherited ones.


Example

 

using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;


namespace ConsoleApplicationinheritence

{

//super class class Animal

{

public void eat()

{

Console.WriteLine("This animal eats food.");

}

}

// Subclass

class Dog : Animal

{

public void bark()

{

Console.WriteLine("The dog barks.");

}

}

// Child Class 2

 

class Cat : Animal

{

public void meow() { Console.WriteLine("The cat meows.");

}

}


class Program

{

static void Main(string[] args)

{

Dog labrador = new Dog();

labrador.eat(); // Inherited method from Animal labrador.bark(); // Method from Dog

Cat cat = new Cat();

cat.eat(); // Inherited from Animal cat.meow(); // Specific to Cat Console.ReadKey();

}

}

}


o/p

This animal eats food. The dog barks.

 

This animal eats food. The cat meows.







MULTILEVEL INHERITANCE


Multilevel inheritance is a type of inheritance in Java where a class inherits from a class that itself inherits from another class. This forms a chain of inheritance, allowing properties and methods to be passed down through multiple levels of classes.

Key Points

It enables reusability of code across multiple levels.

Each child class inherits properties and methods from its immediate parent and all ancestor classes.

Java supports multilevel inheritance, but it does not support multiple inheritance with classes (to avoid ambiguity).


Example


using System;

using System.Collections.Generic;

 

using System.Linq; using System.Text;

using System.Threading.Tasks;


namespace ConsoleApplicationinheritence

{

//super class class Animal

{

public void eat()

{

Console.WriteLine("This mammal walks.");

}

}

// Subclass

class Mammal : Animal

{

public void walk()

{

Console.WriteLine("The dog barks.");

}

}

// Child Class 2 class Dog : Mammal

 

{

public void bark()

{

Console.WriteLine("The dog barks.");

}

}


class Program

{

static void Main(string[] args)

{

Dog dog = new Dog();


// Accessing methods from all levels of inheritance dog.eat(); // From Animal class

dog.walk(); // From Mammal class dog.bark(); // From Dog class Console.ReadKey();

}

}

}


o/p

This mammal walks. The dog barks.

 

The dog barks.


Hierarchical inheritance


When more than one classes inherit a same class then this is called hierarchical inheritance. For example class B, C and D extends a same class A. Lets see the diagram representation of this:















As you can see in the above diagram that when a class has more than one child classes (sub classes) or in other words more than one child classes have the same parent class then this type of inheritance is known as hierarchical inheritance.


Example

using System;

 

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;


namespace ConsoleApplicationhirarchicalinheritance

{

class employee

{

public void salary()

{

Console.WriteLine(20000);

}

}

class Designer :employee

{

public void Develop()


{

Console.WriteLine("Designing");

}

}

class Tester :employee

{

public void Test()

{

Console.WriteLine("Testing");

}

}

class Developer : employee

 

{

public void Develop()

{

Console.WriteLine("Developer");

}

}

class Program

{

static void Main(string[] args)

{

Designer obj = new Designer(); obj.Develop();

obj.salary();

Developer obj1 = new Developer(); obj1.Develop();

obj1.salary();

Tester obj2 = new Tester(); obj2.Test();

obj2.salary(); Console.ReadKey();

}

}

}


Output Designing 20000

Developer 20000

Testing

 

20000


HYBRID INHERITANCE


Hybrid inheritance is a combination of two or more types of inheritance, such as single, multilevel, hierarchical, or multiple inheritance. It is used to model complex relationships between classes. However, Java does not support hybrid inheritance directly through classes because it avoids the ambiguity caused by the Diamond Problem. Instead, hybrid inheritance can be achieved in Java using interfaces.

Key Concepts

Diamond Problem: This occurs when a class inherits from two classes that have a common base class, leading to ambiguity about which method or property to inherit. Java avoids this by not supporting multiple inheritance with classes.

Solution with Interfaces: Java allows multiple inheritance through interfaces, as interfaces do not store implementation, only declarations.


Example

using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;


namespace ConsoleApplicationhirarchicalinheritance

{

class employee

{

public void salary()

{

Console.WriteLine(20000);

}

}

 

class Designer :employee

{

public void Design()


{

Console.WriteLine("Designing");

}

}

class jDesigner : Designer

{

public void jDesigne()


{

Console.WriteLine("Designing");

}

}

class Tester :employee

{

public void Test()

{

Console.WriteLine("Testing");

}

}

class jTester : Tester

{

public void jTest()

{

Console.WriteLine("Testing");

}

}

 

class Developer : employee

{

public void Develop()

{

Console.WriteLine("Developer");

}

}

class jDeveloper : Developer

{

public void jDevelope()

{

Console.WriteLine("Developing");

}

}

class Program

{

static void Main(string[] args)

{

jDesigner obj = new jDesigner(); obj.jDesigne();

obj.Design();

obj.salary();

jDeveloper obj1 = new jDeveloper(); obj1.jDevelope();

obj1.Develop(); obj1.salary();

jTester obj2 = new jTester(); obj2.Test();

obj2.Test(); obj2.salary();

 

Console.ReadKey();

}

}

}


O/P


Designing Designing 20000

Developing Developer 20000

Testing Testing 20000

ABSTRACTION

Abstraction is a concept of simplifying a real world object into its essential features without including background details


Abstract class


An abstract class is declared with the help of abstract keyword.

In c# you are not allowed to create objects of the abstract class or in other words,you cannot use the abstract class directly with the new operator.

Class that contains the abstract keyword with some of methods(not all abstract method) is known as abstract base class

Class that contains the abstract keyword with all of its method is known as pure abstract class.

 

You are not allowed to declare the abstract methods outside the abstract class.

You are not allowed to declare abstract class as sealed class.


SEALED CLASS

Its used to restricted the inheritance features of oops .once a class defined as a sealed class,this class cannot be inherited.in C#,The sealed modifier is used to declare a class sealed.

The sealed keyword word used in before class,


Example using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;


namespace ConsoleApplicationabstractclass

{

abstract class Animal

{

//abstract methods doesnot have body public abstract void animalsound();

//Regular method public void sleep()

{

Console.WriteLine("zzzz");

}

}

//Derived class (inherit from animal)

 

class pig : Animal

{

public override void animalsound()

{

//body

Console.WriteLine("The pig say we weee");

}

}

class Program

{


static void Main(string[] args)

{

pig mypig = new pig(); mypig.animalsound(); mypig.sleep(); Console.ReadKey();

}

}

}

Output

The pig say we weee zzzz


ENCAPSULATION


Wrapping up of data into a single unit known as encapsulation Different types of acces specifiers in c#:

 

c# support 6 types of access specifiers they are as follows


1.private 2.public 3.protected 4.internal

5. protected internal

6. private protected


Private

Member can be accessed within the class only\ example

Namespace privateexamp

{

Public class ABC

{

Private int id;

}

Class program

{

Static void main(string[] args)

{

ABC abc=new ABC(); abc.id=10; console.ReadKey();

}

}

}


ABC.id inaccessible due to its protected level

 

Public


As the name says member can be accessed from any class and any assembles


Example using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;


namespace ConsoleApplicationpublic

{

public class ABC

{

public int id;

}


class Program

{


static void Main(string[] args)

{

ABC abc = new ABC(); abc.id = 10;

Console.WriteLine("ID =" + abc.id); Console.ReadKey();

 

}

}

}


Output ID =10




PROTECTED


Member can be accessed within their class and derived of the same assembly


Example using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;


namespace ConsoleApplicationpublic

{

public class ABC

{

protected int id;

}

class childclass:ABC

{

public void print()

 

{

id = 10; Console.WriteLine(id);

}

}

class Program

{


static void Main(string[] args)

{

childclass obj = new childclass(); obj.print();

Console.ReadKey();


}

}

}

Output 10


Internal


Members can be accessed from anywhere within the same assembly.

Protected internal


Member can be accessed anywhere in the same assembly and also accessible by inheriting that class.

 

POLYMORPHISM



Types of polymorphism

1. static polymorphism/compile time polymorphism/Early binding

2. Dynamic polymorphism/Runtime polymorphism/Latebinding

1. Compile-Time Polymorphism

The mechanism of linking a function with an object during compile time is called early binding it is also static binding.

a) Function Overloading: Multiple functions with the same name but different parameter lists.

b) Operator Overloading: Redefining the behavior of operators for user-defined types.

Function overloading using System;

using System.Collections.Generic;

using System.Linq; using System.Text;

using System.Threading.Tasks; using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;


namespace ConsoleApplicationarea

{

class TestData

 

{

public double area(double a)

{

return a * 3.14;

}

public int area(int a, int b)

{

return a * b;

}

public int area(int a, int b,int c)

{

return a * b *c;

}

}

class Program

{

static void Main(string[] args)

{

TestData obj = new TestData(); double area1 = obj.area(3);

int area2 = obj.area(5, 6); int area3 = obj.area(3,4,5);

Console.WriteLine("Area of circle =" + area1) ; Console.WriteLine("Area of Rectangle =" + area2);


Console.WriteLine("volume of Rectangle =" + area3); Console.ReadKey();

}

}

}

 


Output


Area of circle =9.42 Area of Rectangle =30 volume of Rectangle =60



2. Run-Time Polymorphism

This type of polymorphism is resolved during the execution of the program. It is achieved through:

Function Overriding: A derived class provides a specific implementation of a function already defined in its base class.


Example using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;


namespace ConsoleApplicationoperatoroverloading

{


class baseclass

{

// virtual

public virtual void show()

{

 

Console.WriteLine("Base class");

}

}

class derivedclass : baseclass

{

//Override here

public override void show()

{

Console.WriteLine("Derived class");

}

}

class Program

{

static void Main(string[] args)

{

baseclass obj;

obj = new baseclass(); obj.show();

obj = new derivedclass(); obj.show(); Console.ReadKey();

}

}

}


O/P

Base class Derived class

 

INTERFACE

An interface in Java is a blueprint for a class that defines a set of methods that a class must implement. It is a way to achieve abstraction and multiple inheritance in Java. Interfaces are widely used to define contracts or behaviors that implementing classes must adhere to.

Key Features of Interfaces

Abstract Methods: All methods in an interface are implicitly public and abstract (until Java 8).

Default and Static Methods: From Java 8 onwards, interfaces can have default and static methods with implementations.

Constants: Variables in an interface are implicitly public, static, and final.

Multiple Inheritance: A class can implement multiple interfaces, allowing Java to support multiple inheritance indirectly.

Loose Coupling: Interfaces promote loose coupling by focusing on behavior rather than implementation.


In C# an interface can be defined using the interface keyword .An interface can contain declaration of methods properties indeaers and events.


Interfaces specify what a class must do and not how.

Interface cant have private members

By default all the members of interface are public and abstract

Using interface keyword

Interface cannot contain fields because they represent a particular implementation of data.

Multiple inheritance is possible with the help of interface but not with classes.

Syntax for interface Interface <interfacename>

{

 

//declare events

//Declare indexes

//Declare methods

//declare properties

}

Syntax  for implementing interface Class classname:interfacename



Example

using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;


namespace ConsoleApplicationinterface

{


interface myinterface

{

void Display();

}

interface myinterface1

{

void show();

}

class myclass:myinterface,myinterface1

{

public void Display()

 

{

Console.WriteLine("Hello");

}

public void show()

{

Console.WriteLine("Hai");

}

}

class Program :myclass

{

static void Main(string[] args)

{


Program p = new Program(); p.Display();

p.show(); Console.ReadKey();

}

}

}


Output Hello Hai


Ex

using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

 

using System.Threading.Tasks;


namespace ConsoleApplicationinter

{

interface Animal1

{

void animalsound();


}

class pig :Animal1

{

public void animalsound()

{

Console.WriteLine("The pig Sound :we wee");

}

}

class Program :pig

{

static void Main(string[] args)

{

Program p = new Program(); p.animalsound(); Console.ReadKey();

}

}

}

O/P :- The pig Sound :we wee

 

Base keyword


The ‘base’ keyword ,the derived class is able to access the method .A virtual method is a method that can be redefined in derived classes. A virtual method has an implementation in a base class as well as a derived class.

The keyword base is used to access members of the base class (the parent class) from within a derived (child) class.

It is mainly used for:Calling the base class constructor. Accessing base class methods, properties, or fields that are hidden or overridden in the derived class.


Example

using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;


namespace ConsoleApplicationvirtual

{



class Animal

{

public string Name;

public Animal(string name)

{

Name = name;

 

Console.WriteLine("Animal Constructor called");

}

}


class Dog : Animal

{

public Dog(string name):base(name)


{

Console.WriteLine("The dog constructor called.");

}

}


class Program

{

static void Main()

{

Dog d = new Dog("Buddy"); Console.WriteLine($"Dog's name :{d.Name}"); Console.ReadKey();

}

}


}

 Output

Animal Constructor called The dog constructor called. Dog's name :Buddy

 

The virtual keyword is used for generating a virtual path for its derived classes on implementing method over riding .The virtual keyword is used within a set with an over ride keyword.

Override keyword key word is used in the derived class of the baseclass in order to override the base class method

.The override method is used with the virtual keyword


Example

using System;


class Animal

{

// Virtual method in the base class public virtual void Speak()

{

Console.WriteLine("The animal makes a sound.");

}

}


class Dog : Animal

{

// Overriding the virtual method in the derived class public override void Speak()

{

Console.WriteLine("The dog barks.");

}

}

 

class Program

{

static void Main()

{

Animal myAnimal = new Animal();

myAnimal.Speak(); // Output: The animal makes a sound.


Animal myDog = new Dog(); myDog.Speak(); // Output: The dog barks.

}

}



virtual: The Speak method in the Animal class is marked as virtual, allowing it to be overridden in derived classes.

override: The Speak method in the Dog class uses the override keyword to provide a new implementation for the base class's Speak method.


CONSTRUCTOR

Constructor is a member function that invoke automatically when the object is created.

Constructor of a class must have the same name as the class name in which it resides.

A Constructor can not be abstract, final, static and Synchronized

Within a class, you can create only one static constructor.

A constructor doesn't have any return type, not even void.

A static constructor cannot be a parameterized constructor.

A class can have any number of constructors.

Access modifiers can be cued in constructor declaration to control its access ie, which other class can call the constructor

 



Types of constructors


a) Default constructor: Constructor with no parameters is called default constructor.

b) Parameterized constructor: Constructor with parameters called parameterized Constructor .


Example

using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;


namespace ConsoleApplicationconstructor

{

class myconstructor

{

public int a, b;

public myconstructor(int x,int y)

{

a = x;

b = y;

}

public myconstructor()//default constructor

{

a = 200;

 

b = 275;

}

}

class Program

{

static void Main(string[] args)

{

myconstructor v = new myconstructor(100, 175); Console.WriteLine("value of a=" + v.a); Console.WriteLine("value of b=" + v.b); myconstructor v1 = new myconstructor(); Console.WriteLine(v1.a); Console.WriteLine(v1.b);


Console.ReadKey();


}

}

}


Output

value of a=100 value of b=175 200

275

DISTRUCTOR


Distructor is a member function that invoke automatically when the object is destroyed. A distructor works opposite to

 

constructor,its destruct the objects of classes. It can be defined only once in a class.


characteristics of distructor


* In c#, distructor can be used only in classes and a class can contain only one distructor.


* the distructor in class can be represented by using tilde (~) operator.


* The distructor in c# won't accept any parameters and access modifiers.


*The distructor will invoke automatically, whenever on instance of a class is no longer needed.




* The distructor automatically invoked by garbage collector (GC) whenever the class object that are no longer needed in the application.


* A distructor is a unique to its class is, there cannot be more than one distructor in a class


* It cannot be defured in Structure. It is only used wit classes.

* It cannot be overloaded or inherited.

* it is called when the program exit.

* internally ,destructor called the finalized method on the base class of object


Example

 

using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;


namespace ConsoleApplication4distructor

{

class user

{

public user()

{

Console.WriteLine("As instance of class created");


}

~user()

{

Console.WriteLine("As instance of class distroyed");


}

}

class Program

{

static void Main(string[] args)

{

Details(); GC.Collect(); Console.ReadLine();


}

 

public static void Details()

{

user us = new user(); Console.ReadKey();


}

}

}

Output

As instance of class created As instance of class distroyed

Named and Optional parameters Named parameter:-

Named parameter allow developers to pass a method arguments

with parameter names.This features allows us to associated argument name its value at the time of function calling.

When we make named arguments ,the arguments are evaluated in the order in which they are passed.

It helps us,not to remember the order of parameters,if we know the parameters name we can pass that in any order.


Example using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace ConsoleApplication4named

{

class Program

{

public string GetFullname(string strFirstName,string strLastName)

{

return strFirstName + " " + strLastName;

}

static void Main(string[] args)

{

Program objpgm = new Program();

  string strFullname = objpgm.GetFullname("Anjana", "Anil");

 string strFullname1 = objpgm.GetFullname(strFirstName:"Anjana", strLastName: "Anil");

string strFullname2 = objpgm.GetFullname(strLastName : "Anil", strFirstName: "Anjana");

Console.WriteLine(strFullname); Console.WriteLine(strFullname1); Console.WriteLine(strFullname2); Console.ReadKey();

}

}

}


output Anjana Anil Anjana Anil Anjana Anil

 

Optional parameters

The optional parameters contains a default value in function.

It we do not pass optional argument value at calling time ,the default value is used.

It helps to executed arguments for some parameters.


Example using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;


namespace ConsoleApplicationoptional

{

class Program

{

public void scholoar(string strfname,string strlname,int iage=20,string strbranch="ComputerScience")

{

Console.WriteLine("First Name : {0}", strfname); Console.WriteLine("Last Name : {0}", strlname); Console.WriteLine("Age : {0}", iage); Console.WriteLine("Branch: {0}", strbranch);

}

static void Main(string[] args)

{

Program p = new Program(); p.scholoar("Anjana", "Anil");

p.scholoar("Anzi", "Beegum", 30);

 

p.scholoar("Diya", "krishna", 27, "information Technolgy"); Console.ReadKey();

}

}

}


Output

First Name : Anjana Last Name : Anil Age : 20

Branch: ComputerScience First Name : Anzi

Last Name : Beegum Age : 30

Branch: ComputerScience First Name : Diya

Last Name : krishna Age : 27

Branch: information Technolgy


Value Types and Reference Type [call by value and call by reference] Value type:


A data type is called a value type if it stores its data directly in its own memory space. This means the variable contains the actual value, not a reference to the value.


- All value types derive from System.ValueType.

 

- Value types are usually stored on the stack (though the exact memory location depends on how they are used).

- When you create a value type variable, memory is directly allocated to store the value.


Examples of value types in C#:

- int

- float

- char

- bool

- struct

- enum Example:

int a = 10;

int b = a; // b holds a copy of the value 10



In the above, a and b are independent; changing one won’t affect the other

Reference type

In programming, especially in C#, a reference type is a type that stores a reference (address) to the memory location where the actual data is held. This means multiple variables can refer to the same object in memory.


Examples of Reference Types:

 

- Class

- Array

- String

- Interface

- Delegate

- Object


Example in C#: csharp

class Person {

public string Name;

}


Person p1 = new Person(); p1.Name = "Alice";


Person p2 = p1; p2.Name = "Bob";


Console.WriteLine(p1.Name); // Output: Bob (because p1 and p2 point to the same object)


Example using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace ConsoleApplicationReferncetype

{

class person

{

public int age;

}

class Program

{

static void square(person a,person b)

{

a.age = a.age * a.age; b.age = b.age * b.age;

Console.WriteLine(a.age + " " + b.age);

}

static void Main(string[] args)

{

person p1 = new person(); person p2 = new person(); p1.age = 5;

p2.age = 10;

Console.WriteLine(p1.age + " " + p2.age); square(p1, p2);

Console.WriteLine(p1.age + " " + p2.age); Console.WriteLine("pass any key to exit"); Console.ReadKey();

}

}

 

}

Output 5 10

25 100

25 100

pass any key to exit


Delegate

In C#, a delegate is a type-safe function pointer — it holds a reference to a method with a specific signature and return type.

A delegate is a reference type variable that holds the reference to a method. This reference can be changed at runtime.


A delegate can be declared using the delegate keyword.


Delegates are one of the main built-in types in .NET. A delegate is a class, which is used to create and invoke methods at runtime


Syntax:

csharp

delegate returnType DelegateName(parameterList);



Example:

csharp

// Define a delegate

delegate void Greet(string name);

 

// Method matching the delegate signature void SayHello(string name) {

Console.WriteLine("Hello " + name);

}


// Use the delegate Greet greet = SayHello;

greet("John"); // Output: Hello John



Key Points:

- Delegates can point to static or instance methods.

- You can use them to pass methods as parameters.

- Multicast delegates allow combining multiple methods.

- Events in C# are built on delegates. Why use delegates?


In many scenarios, programmers need to pass methods as parameters to other methods. For this purpose, delegates are used.


Example using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks; namespace ConsoleApplication4Delegate

 

{

delegate int calculate(int n); class Program

{

static int number = 100; public static int add(int n)

{

number=(number + n); return number;

}

public static int mul(int n)

{

number= number * n; return number;

}

public static int getNumber()

{

return number;

}

static void Main(string[] args)

{

calculate c1 = new calculate(add); calculate c2 = new calculate(mul); c1(20);

Console.WriteLine("After c1 delegate ,Number is :" + getNumber());

c2(3);

 

Console.WriteLine("After c2 delegate ,Number is :" + getNumber());

Console.ReadKey();


}

}

}


Output

After c1 delegate ,Number is :120 After c2 delegate ,Number is :360




Name space

It is a collection of names where is each name is unique

They form of logical boundary for a group of classes

Name space must be specified in protect properties

ASSEMBLY

It is an output unit

It is a unit of deployment and unit of version

Assemblies contain MSIL code.

Assemblies are self Describing{eg:metaData,manifest}

It is the primary building block of a .Net framework application

 

It is a collection of functionality that is built versioned and delayed as a single implementation unit(as one or more files)

All managed types and resources are marked either as accessible only with in their implementation unit,or by code outside that unit.

//dll files or exe files.. Already build and reference them in to the project



✅ Namespace:

- A namespace is a container for classes, interfaces, structs,

enums, and delegates.

- It is used to organize code and avoid name conflicts.

- Think of it like a folder structure in your project.


Example:

csharp

namespace MyProject.Utilities { class Calculator {

// code

}

}



---

 

✅ Assembly:

- An assembly is a compiled code library used for deployment,

versioning, and security.

- It is a .dll or .exe file that contains compiled C# code.

- Assemblies can have one or more namespaces inside them.

| Feature | Namespace | Assembly

|

|----------------|--------------------------------------|----------------------

- |

| Definition | Logical group of related classes | Physical unit of compiled code |

| Type | Logical (used during coding) | Physical (used during execution) |

| File type | No file created | .dll or .exe file

|

| Purpose | Organize code | Deploy and run application


Example using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;


namespace ConsoleApplicationnamespaces

{

 

namespace first

{

class namespace_C1

{

public void fun()

{

Console.WriteLine("My First namespace");

}

}

}

namespace second

{

class namespace_C2

{

public void fun()

{

Console.WriteLine("My second namespace");

}

}

}

class Program

{

static void Main(string[] args)

{

first.namespace_C1 f1 = new first.namespace_C1();

second.namespace_C2 f2 = new

second.namespace_C2();

 

f1.fun();

f2.fun(); Console.ReadKey();


}

}

}


Output

My First namespace My second namespace


Class Library

Its Globalvalues class in ayurlive i have done in touchq

File->New ->project->SearchClassLibrary and select write claa name->ok

// ClassLibrary1.h #pragma once

using namespace System; namespace ClassLibrary1 {

public ref class Class1

{

public: int fun()

 

{

return 10;

}

// TODO: Add your methods for this class here.

};

}


Its only build not have output


File->new ->project->console.FrameWork->ok->create solution explore

Refrences->add reference->browse->click

Class path of class (ClassLibrary1 )->Debug->dll file ->select the file->ok


using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;


namespace ConsoleApplicationAsd

{

class Program

{

static void Main(string[] args)

{

 

ClassLibrary1.Class1 new1 = new

ClassLibrary1.Class1();

int i = new1.fun();

Console.WriteLine("The number of function is " + i); Console.ReadKey();

}

}

}


Output

The number of function is 10

Exception

Exception is an abnormal situation Exception handling

To handle the exception situation C# use the following keywords Keyword


Key Word Definition

try Used to define a try block.This Block holds the code that my thrown an exception

catch Used to define a catch blocks.the block catches the exception throw by the try block

finally The block holds the default code

throw Throw an exception manually

 

Syntax Try

{

}

catch()

{

}

Finally

{

Default code

}


1. Divided by zero Exception

using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;


namespace ConsoleApplicationException

{

class Program

{

static void Main(string[] args)

{

try

{

int a = 10;

 

int b = 0; int x = a / b;

}

catch(Exception ex)

{

Console.WriteLine(ex);

}


Console.WriteLine("Rest of the code"); Console.ReadKey();

}

}

}


Output


System.DivideByZeroException: Attempted to divide by zero.

at ConsoleApplicationException.Program.Main(String[] args) in D:\ayurlive-windows\BanquetManagement\ConsoleApplicationExc eption\ConsoleApplicationException\Program.cs:line 17

Rest of the code

2. Index out of Range exception


a) stringindexoutofRangeException

b) ArrayIndexoutofRangeException

 

StringIndexOutOfRangeException using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;


namespace ConsoleApplicationException

{

class Program

{

static void Main(string[] args)

{

string Example = "Hello World"; try

{

char outboundchar= Example[20];

}

catch(Exception ex)

{

Console.WriteLine("Caugn an exception "+ ex); Console.ReadKey();

}



}

}

 

}

Output

Caught an exception System.IndexOutOfRangeException: Index was outside the bounds of the array.

at System.String.get_Chars(Int32 index)

at ConsoleApplicationException.Program.Main(String[] args) in

D:\ayurlive-windows\BanquetManagement\ConsoleApplic ationException\ConsoleApplicationException\Program.cs:l ine 16

ArrayIndexOutofRangeException

using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;


namespace ConsoleApplicationException

{

class Program

{

static void Main(string[] args)

{

string[] color = { "Blue", "Green", "Red" }; try

{

Console.WriteLine(color[5]);

 

}

catch(Exception ex)

{

Console.WriteLine(" exception occures "+ ex); Console.ReadKey();

}



}

}

}



exception occures System.IndexOutOfRangeException: Index was outside the bounds of the array.

at ConsoleApplicationException.Program.Main(String[] args) in

D:\ayurlive-windows\BanquetManagement\ConsoleApplic ationException\ConsoleApplicationException\Program.cs:l ine 16


3. FileNotFoundException using System;

using System.Collections.Generic; using System.IO;

using System.Linq; using System.Text;

 

using System.Threading.Tasks;


namespace ConsoleApplicationException

{

class Program

{

static void Main(string[] args)

{

try

{

using (StreamReader reader = new

StreamReader("textMatrix.txt"))

{

Console.WriteLine(reader.ReadToEnd());

}

}

catch(Exception ex)

{

Console.WriteLine( ex); Console.ReadKey();

}

Console.ReadKey();


}

}

}

 


System.IO.FileNotFoundException: Could not find file 'D:\ayurlive-windows\BanquetManagement\ConsoleApplic ationException\ConsoleApplicationException\bin\Debug\te xtMatrix.txt'.

File name:

'D:\ayurlive-windows\BanquetManagement\ConsoleApplic ationException\ConsoleApplicationException\bin\Debug\te xtMatrix.txt'

at System.IO. Error.WinIOError(Int32 errorCode, String maybeFullPath)

at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)

at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)

at System.IO.StreamReader..ctor(String path, Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize, Boolean checkHost)

at System.IO.StreamReader..ctor(String path)

 

at ConsoleApplicationException.Program.Main(String[] args) in

D:\ayurlive-windows\BanquetManagement\ConsoleApplic ationException\ConsoleApplicationException\Program.cs:l ine 16


4. InvalidOperationalException


using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;


namespace ConsoleApplicationinvalid1

{

class Program

{


static void Main(string[] args)

{

List<int> numbers = new List<int> { 1, 2, 3, 4, 5 }; try

{

foreach(int number in numbers)

{

if(number==3)

 

{

numbers.Remove(number);

}

}

}

catch(InvalidOperationException e)

{

Console.WriteLine("caught an invalid operation exception" + e.Message);

foreach(int number in numbers)

{

Console.WriteLine(number);

}

Console.ReadKey();

}

}

}

}


Output

caught an invalid operation exceptionCollection was modified; enumeration operation may not execute.

1

2

4

5

 

C# Break

You have already seen the break statement used in an earlier chapter of this tutorial .it is used to “jump out” of switch statement.

The break statement can also be used to jump out of a loop.

using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;


namespace ConsoleApplicationbreak

{

class Program

{

static void Main(string[] args)

{

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

{

if(i==4)

{

break;

}

Console.WriteLine(i);

}

Console.ReadKey();

 

}

}

}


Output 0

1

2

3

C# continue

The continue statement breaks one iteration (in the loop

),if a specified condition occurs and continuous with the next iteration in the loop


using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;


namespace ConsoleApplicationbreak

{

class Program

{

static void Main(string[] args)

{

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

 

{

if(i==4)

{

continue;

}

Console.WriteLine(i);

}

Console.ReadKey();

}

}

}


Output 0

1

2

3

5

6

7

8

9


Class members

Fields and method inside classes are often referred to as class members

using System;

 

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;


namespace ConsoleApplicationbreak

{

class Program

{

string color = "Red"; int maxspeed = 200;

static void Main(string[] args)

{

Program obj = new Program(); Console.WriteLine(obj.color); Console.WriteLine(obj.maxspeed); Console.ReadKey();

}

}

}

Output Red 200

 

Extension method

Extension methods in c# allow you to add new methods to existing type without modifying the original type or creating a new divided type.They are defined as stattic methods in stattic classes and the first parameter of the method specifies the type that the methods operates on proceed by the this keyword.

using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;


namespace ConsoleApplicationbreak

{

public static class extensionmethos

{

 


value)

{

 

public static string UppercaseFirstletter(this string



if (value.Length > 0)

{

 

char[] array = value.ToCharArray(); array[0] = char.ToUpper(array[0]); return new string(array);

}

return value;

 

}

}

public class Program {

static void Main(string[] args)

{

string value = "dotnet";

value = value.UppercaseFirstletter(); Console.WriteLine(value); Console.ReadKey();

}

}

}


Output Dotnet

1) Pgm to check reverse a number using System;

using System.Collections.Generic;

using System.Linq; using System.Text;

using System.Threading.Tasks;


namespace ConsoleApplicationbreak

{

 

public class Program {

static void Main(string[] args)

{


Console.WriteLine("Enter a number");

int n = Convert.ToInt32(Console.ReadLine()); int d = 0;

d = n; int z=0;

while(d%10>1)

{

z = d % 10;

Console.Write(z); d = (n - z) / 10;

n = d;

}

Console.ReadKey();

}

}

}




Output

Enter a number 2345

5432

 

Planidrome using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;


namespace ConsoleApplicationbreak

{


public class Program {

static void Main(string[] args)

{


Console.WriteLine("Enter a number");

int number =

Convert.ToInt32(Console.ReadLine()); int originalnumber = number; int reversenumber = 0;

int tempnumber=number; while(number>0)

{

int digit = number % 10;

reversenumber = reversenumber * 10 + digit; number /= 10;

}

Console.WriteLine(reversenumber);

 

if(tempnumber==reversenumber)

{

Console.WriteLine("The number is palindrome");

}

 

else

{


palindrome");

}

 



Console.WriteLine("The number is not

 

Console.ReadKey();

}

}

}


Output

Enter a number 232

232

The number is palindrome


Tokens

Token refers to a fundamental unit of code that the compiler uses to understand the structure and meaning of the source code. Here are some examples of tokens in C#:

 

1.  Keywords: These are reserved words with predefined meanings in the C# language, such as class, if, for, while, int, etc.

 

2.  Identifiers: These are names given to entities in a program, such as variables, functions, classes, etc. Identifiers can include letters, digits, and underscores, but must follow certain naming conventions and cannot be a C# keyword.

 

3.  Literals: These are constant values explicitly specified in the code. For example, 42 is an integer literal, "Hello" is a string literal, true is a Boolean literal, etc.

 

4.  Operators: These are symbols used to perform operations on variables or values, such as +, -,

*, /, &&, ||, ==, =, etc.

 

5.  Punctuation Marks: These include symbols like parentheses (), braces {}, square brackets [], semicolons; commas, periods., etc., used for grouping, separating, or terminating code elements.

 

OPERATORS

The followings are the operators in c#:

 

1.  Arithmetic operators

 

2.  Assignment operators

 

3.  Logical operators

 

4.  Conditional operators

 

5.  Relational operators

 

6.  Increment operator

 

7.  Decrement operators


Arithmetic operators

 

+ - * / % using System;

using System. Collections. Generic; using System.Linq;

using System.Text;

 

using System.Threading.Tasks;

 

 

 

namespace arithmetic

 

{

 

internal class Program

 

{

 

static void Main(string[] args)

 

{

 

int a = 20; int b = 10;

Console. WriteLine("SUM=" + (a + b)); Console. WriteLine("difference=" + (a - b)); Console. WriteLine("product=" + (a * b)); Console. WriteLine("division=" + (a / b)); Console. WriteLine("modulus=" + (a % b));


 

 

 

}

 

}

 

}

 

======================================================================

 

 

 

Assignment operators

 

+= -= *= /= %=

 

using System;

 

using System.Collections.Generic; using System.Linq;

using System.Text;

 

using System.Threading.Tasks;

 

 

 

namespace assignment operator

 

{

 

internal class Program

 

{

 

static void Main(string[] args)

 

{

 

int a = 20;


a += 3;

 

Console. WriteLine(a); a -= 2;

Console. WriteLine(a); a *= 3;

Console. WriteLine(a); a /= 4;

Console. WriteLine(a); a %= 2;

Console. WriteLine(a);

 

}

 

}

 

}

 

======================================================================

 

 

 

Conditional operators

 

 

 

Ø Syntax: (condition)? True: false; Console. WriteLine("Enter 2 numbers:");

 

 

Int a=Convert.ToInt32(Console.ReadLine()); int b=Convert.ToInt32(Console.ReadLine());


int max = (a > b) ? a : b; Console. WriteLine("big= “+max);

 

======================================================================

 

 

 

Logical operators

 

( AND &&, OR || , NOT EQUALTO !=)

 

 

 

using System;

 

using System.Collections.Generic; using System.Linq;

using System.Text;

 

using System.Threading.Tasks;

 

 

 

namespace logical operators

 

{

 

internal class Program

 

{

 

static void Main(string[] args)

 

{

 

 

 

Console. WriteLine("Enter 4 numbers");

 

 

 

int a = Convert.ToInt32(Console.ReadLine());


int b = Convert.ToInt32(Console.ReadLine());

 

 

 

int c = Convert.ToInt32(Console.ReadLine()); int d = Convert.ToInt32(Console.ReadLine());

 

 

 

 

 

 

if ((a > b) && (a > c) && (a > d))

 

 

 

Console. WriteLine("big= " + a);

 

 

 

else if ((b > a) && (b > c) && (b > d))

 

 

 

Console. WriteLine("big= " + b);

 

 

 

else if (c > d)

 

 

 

Console. WriteLine("big= " + c);

 

 

 

else


Console. WriteLine("big=" + d);

 

}

 

}}

 

======================================================================

 

 

 

Logical OR

 

Console. WriteLine("Enter a character");

 

char a = Convert.ToChar(Console.ReadLine());’ if((a=='a' ) || (a=='e') || (a=='i') || (a=='o') ||(a=='u'))

{

 

Console. WriteLine("Vowels");

 

}

 

else { Console. WriteLine("Not a vowel"); } Not equal

Console. WriteLine("Enter a number");

 

 

 

int a = Convert.ToInt32(Console.ReadLine()); if (a % 2 == 0)

Console. WriteLine("even"); if (a % 2 != 0)

Console. WriteLine("ODD");

 

======================================================================


Increment/Decrement Operators

 

 

 

 

 

Console. WriteLine("Enter a number");

 

int a = Convert.ToInt32(Console.ReadLine()); a++; //increment

Console. WriteLine(a); a--; //decrement

Console. WriteLine(a);

 

 

C# Type casting

 

Type casting is when you assign a value of one data type to another type In C3 ,ther are two types of casting

 

a)     Implicit casting (automatically): converting a smaller type to a larger type size; char->int->long->float->double

 

b)   Explicit casting (manually) :-> converting a larger type to smaller size type double->float->long->int->char

 

Type conversion method

 

It is also possible to convert data types explicitly by using built-in methods ,such as convert to boolean ,convert to double ,convert to


string,convert to int 32,convert to int64.



What is an IL?

 

(IL)Intermediate Language is also known as MSIL (Microsoft Intermediate Language) or CIL

(Common Intermediate Language). All .NET source code is compiled to IL.

This IL is then

converted to machine code at the point where the software is installed, or at run-time by a Just-InTime (JIT) compiler.

 

What is a CLR?

 

Full form of CLR is Common Language Runtime and it forms the heart of the .NET framework.All Languages have runtime and its the responsibility of the runtime to take care of the code execution of the program.For example VC++ has MSCRT40.DLL,VB6 has MSVBVM60.DLL , Java has Java Virtual Machine etc. Similarly .NET has CLR.Following are the responsibilities of CLR

 √ Garbage Collection :- CLR automatically manages memory thus eliminating memory leaks. When objects are not referred GC automatically releases those memory thus providing efficient memory management.

 √ Code Access Security :- CAS grants rights to program depending on the security configuration of the machine.Example the program has rights to edit or create a new file but the security configuration of machine does not allow the program to delete a file.CAS will take care that the code runs under the environment of machines security configuration.

√ Code Verification :- This ensures proper code execution and type safety while the code runs.It prevents the source code to perform illegal operations such as accessing invalid memory locations etc.

√ IL( Intermediate language )-to-native translators and optimizer’s :- CLR uses JIT and compiles the IL code to machine code and then executes. CLR also determines, depending on the platform, what is the optimized way of running the IL code.


What is a CTS?

 

In order that two languages communicate smoothly CLR has CTS (Common Type System).Example in VB you have “Integer” and in C++ you have “long” these datatypes are not compatible so the interfacing between them is very complicated. In order that two different languages can communicate Microsoft introduced the Common Type System. So “Integer” datatype in VB6 and “int” datatype in C++ will convert it to System.int32 which is a datatype of CTS.CLS which is covered in the coming question is a subset of CTS.

 

What is a CLS(Common Language Specification)?

This is a subset of the CTS which all .NET languages are expected to support.It was always a dream of microsoft to unite all different languages in to one umbrella and CLS is one step towards that.Microsoft has defined CLS which are nothing but guidelines that language to follow so that it can communicate with other .NET languages in a seamless manner

 

 

 

 

 

 

 

 

 

 

 

 

 

If-else-if

using System;


using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace ConsoleApplicationifelseif

{

class Program

{

static void Main(string[] args)

{

Console.WriteLine("Enter a number");

int a = Convert.ToInt32(Console.ReadLine()); if (a == 1)

Console.WriteLine("Sunday"); else if (a == 2)

Console.WriteLine("Monday"); else if (a == 3)

Console.WriteLine("Tuesday"); else if (a == 4)

Console.WriteLine("Wednesday"); else if (a == 5)

Console.WriteLine("Thursday"); else if (a == 6)

Console.WriteLine("Friday"); else

Console.WriteLine("Invalid"); Console.ReadKey();

}

}


}

 

Switch case

using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace ConsoleApplicationswitchcase

{

class Program

{

static void Main(string[] args)

{

Console.WriteLine("enter a number");

int a = Convert.ToInt32(Console.ReadLine()); switch(a)

{

case 1:

Console.WriteLine("Sunday"); break;

case 2:

Console.WriteLine("monday"); break;

case 3:

Console.WriteLine("Tuesday"); break;

case 4:

Console.WriteLine("Wednesday");


break; case 5:

Console.WriteLine("Thersday"); break;

case 6:

Console.WriteLine("friday"); break;

case 7:

Console.WriteLine("saturday"); break;

default:

Console.WriteLine("invalid"); break;

}

Console.ReadKey();

}

}

}

 

Switch case operator

using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace ConsoleApplicationoperator

{

class Program

{


static void Main(string[] args)

{

Console.WriteLine("Enter two number");

int a = Convert.ToInt32(Console.ReadLine()); int b = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Enter your choice");

Char c = Convert.ToChar(Console.ReadLine()); switch(c)

{

case '+':

Console.WriteLine("sum =" + (a + b)); break;

case '-':

Console.WriteLine("difference =" + (a - b)); break;

case '*':

Console.WriteLine("Product =" + (a * b)); break;

case '/':

Console.WriteLine("division =" + (a /b)); break;

default:

Console.WriteLine("invalid"); break;

}

Console.ReadKey();

}

}

}


Biggest of 3 numbers

 

using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace ConsoleApplicationbiggest

{

class Program

{

static void Main(string[] args)

{

Console.WriteLine("Enter 3 numbers :");

int a = Convert.ToInt32(Console.ReadLine()); int b = Convert.ToInt32(Console.ReadLine()); int c = Convert.ToInt32(Console.ReadLine()); if((a>b) && (a>c))

{

Console.WriteLine(a + " is largest");

}

else if ((b> a) && (b > c))

{

Console.WriteLine(b + " is largest");

}

else

Console.WriteLine(c + " is largest");


Console.ReadKey();

}

}

}

 

OR

 

using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace ConsoleApplicationvvowels

{

class Program

{

static void Main(string[] args)

{

Console.WriteLine("Enter letter");

char c =Convert.ToChar(Console.ReadLine()); if(c=='a'||

c=='A'||c=='e'||c=='E'||c=='i'||c=='I'||c=='o'||c=='O'||c=='u'||c=='U')

{

Console.WriteLine("The character is Vowel");

}

else

{


Console.WriteLine("The character is not Vowel");

}

Console.ReadKey();

}

}

}

 

While loop using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace ConsoleApplicationWhileloop

{

class Program

{

static void Main(string[] args)

{

Console.WriteLine("Enter the limit of loop"); int iNo = Convert.ToInt32(Console.ReadLine()); int i = 1;

Console.WriteLine("The Numbers are"); while (i<= iNo)


{

Console.WriteLine(i); i++;

}

Console.ReadKey();

}

}

}

 

 

using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace ConsoleApplicationmultiplicationtable

{

class Program

{

static void Main(string[] args)

{

Console.WriteLine("which multiplication table you want?"); int imul = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Enter limit you want print");

int iwp = Convert.ToInt32(Console.ReadLine()); int i = 1;

while(i<=iwp)


{

Console.WriteLine(i + "*" + imul + "=" + i * imul); i++;

}

Console.ReadKey();

}

}

}

 

 

do-while using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace ConsoleApplicationmultiplicationtable

{

class Program

{

static void Main(string[] args)

{

Console.WriteLine("which multiplication table you want?"); int imul = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Enter limit you want print");


int iwp = Convert.ToInt32(Console.ReadLine()); int i = 1;

do

{

Console.WriteLine(i + "*" + imul + "=" + i * imul); i++;

} while (i <= iwp);

 

Console.ReadKey();

}

}

}

 

 

for-loop using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace ConsoleApplicationmultiplicationtable

{

class Program

{

static void Main(string[] args)


{

Console.WriteLine("which multiplication table you want?"); int imul = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Enter limit you want print");

int iwp = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Multiplication table :");

 

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

{

 

Console.WriteLine(i + "*" + imul + "=" + i * imul);

 

 

}

Console.ReadKey();

}

}

}

 

using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace ConsoleApplicationmultiplicationtable

{

class Program


{

static void Main(string[] args)

{

Console.WriteLine("which multiplication table you want?"); int imul = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Enter limit you want print");

int iwp = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Multiplication table :");

 

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

{

 

// Console.WriteLine(i + "*" + imul + "=" + i * imul); Console.WriteLine("{0} * {1} ={2}", i,imul,i*imul);

 

 

}

Console.ReadKey();

}

}

}

o/p

which multiplication table you want? 4

Enter limit you want print 10

Multiplication table : 1 * 4 =4


2 * 4 =8

3 * 4 =12

4 * 4 =16

5 * 4 =20

6 * 4 =24

7 * 4 =28

8 * 4 =32

9 * 4 =36

10 * 4 =40

febinocii series using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace ConsoleApplicationfebinocii

{

class Program

{

static void Main(string[] args)

{

Console.WriteLine("Enter the febinocii limit"); int ifebi = Convert.ToInt32(Console.ReadLine()); int first = 0, second = 1, next; Console.WriteLine("the febinocii series are");


Console.Write(first + " " + second + " "); for(int i=2;i<ifebi;i++)

{

next = first + second; Console.Write(next + " "); first = second;

second = next;

}

Console.ReadKey();

}

}

}

 

 

sum of digits using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace ConsoleApplicationsum

{

class Program

{

static void Main(string[] args)

{

Console.WriteLine("Enter the starting number");


int isNo = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Enter the Last number");

int iLNo = Convert.ToInt32(Console.ReadLine()); int sum = 0;

for (int i = isNo; i <=iLNo;i++)

{

if(isNo==iLNo)

{

sum =isNo;

}

sum += i;

}

Console.WriteLine("Sum =" + sum); Console.ReadKey();

}

}

}

 

 

array read write and using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace ConsoleApplicationForeachreadandprint

{


class Program

{

static void Main(string[] args)

{

Console.WriteLine("Enter the number of element"); int size = int.Parse(Console.ReadLine());

int[] numbers = new int[size]; Console.WriteLine("Enter the elements"); for(int i=0;i<size;i++)

{

Console.Write("Element {"+i+" 1 }:"); numbers[i] = int.Parse(Console.ReadLine());

 

}

Console.WriteLine("Array elements are :"); foreach(int num in numbers)

{

Console.WriteLine(num);

}

Console.ReadKey();

}

}

}

 

 

conditional operator using System;


using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace ConsoleApplicationconsitionaloperator

{

class Program

{

static void Main(string[] args)

{

Console.WriteLine("Enter 2 numbers");

int a = Convert.ToInt32(Console.ReadLine()); int b = Convert.ToInt32(Console.ReadLine()); int max = (a > b) ? a : b; Console.WriteLine("Big =" + max); Console.ReadKey();

}

}

}

 

Date and Time using System;

using System.Collections.Generic; using System.Linq;

using System.Text;


using System.Threading.Tasks;

 

namespace ConsoleApplicationDateandtime

{

class Program

{

static void Main(string[] args)

{

Console.WriteLine("Date ="+ DateTime.Now); Console.WriteLine("Date =" + DateTime.Now.ToString()); Console.WriteLine("Date =" +

DateTime.Now.ToLongDateString()); Console.WriteLine("Date =" + DateTime.Now.ToShortDateString()); Console.WriteLine("Date =" + DateTime.Now.ToLongTimeString()); Console.WriteLine("Date =" + DateTime.Now.ToShortTimeString());

Console.WriteLine("Date =" + DateTime.Now.Year); Console.WriteLine("Date =" + DateTime.Now.Month); Console.WriteLine("Date =" + DateTime.Now.Day); Console.WriteLine("Date =" + DateTime.Now.Hour); Console.WriteLine("Date =" + DateTime.Now.Minute); Console.WriteLine("Date =" + DateTime.Now.Second); Console.WriteLine("Date =" + DateTime.Now.Millisecond); Console.ReadKey();

}

}


}

string properties using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace ConsoleApplicationstringproperties

{

class Program

{

static void Main(string[] args)

{

string str = "TrivandrumKollam"; Console.WriteLine(str); Console.WriteLine("length =" + str.Length); Console.WriteLine(str.Substring(5)); Console.WriteLine(str.Substring(3, 7));

Console.WriteLine(str.Remove(3, 4)); Console.WriteLine(str.Replace("i", "z")); Console.WriteLine(str.PadLeft(40, '*')); Console.WriteLine(str.PadRight(40, '*')); Console.ReadKey();

}

}

}


o/p TrivandrumKollam length =16 ndrumKollam vandrum TrirumKollam TrzvandrumKollam

************************TrivandrumKollam TrivandrumKollam************************

 

 

math properties using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace ConsoleApplicationmathprop

{

class Program

{

static void Main(string[] args)

{

Console.WriteLine(Math.PI);


Console.WriteLine(Math.Max(5,10)); Console.WriteLine(Math.Min(5, 10)); Console.WriteLine(Math.Sqrt(64)); Console.WriteLine(Math.Abs(-4.7)); Console.WriteLine(Math.Round(9.99)); Console.ReadKey();

}

}

}

 

o/p 3.14159265358979

10

5

8

4.7

10

 

 

LINQ(Language integrated query)

 

Array methods ,such as min,max, and sum can be found in the system.Linq namespace,manage the query

using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;


namespace ConsoleApplicationLinq

{

class Program

{

static void Main(string[] args)

{

int[] mynumber = { 5, 1, 8, 9 }; Console.WriteLine("Largest number is"); Console.WriteLine(mynumber.Max()); Console.WriteLine("smallest number is"); Console.WriteLine(mynumber.Min()); Console.WriteLine("sum of number is"); Console.WriteLine(mynumber.Sum()); Console.ReadKey();

}

}

}

 

 

o/p

Largest number is 9

smallest number is 1

sum of number is 23


sort

using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace ConsoleApplicationSort

{

class Program

{

static void Main(string[] args)

{

int[] a = new int[5]; Console.WriteLine("Enter five numbers"); for (int i = 0; i < 5; i++)

{

a[i] = Convert.ToInt32(Console.ReadLine());

}

Console.WriteLine("The number of ascending order"); Array.Sort(a);

for(int i=0;i<5;i++)

{

Console.WriteLine(a[i]);

}

Console.ReadKey();

}


}

}

 

Enter five numbers 5

2

6

9

1

The number of ascending order 1

2

5

6

9

 

descending order using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace ConsoleApplicationSort

{

class Program


{

static void Main(string[] args)

{

int[] a = new int[5]; Console.WriteLine("Enter five numbers"); for (int i = 0; i < 5; i++)

{

a[i] = Convert.ToInt32(Console.ReadLine());

}

Console.WriteLine("The number of descending order"); Array.Sort(a);

Array.Reverse(a); for(int i=0;i<5;i++)

{

Console.WriteLine(a[i]);

}

Console.ReadKey();

}

}

}

 

 

Enter five numbers 12

4

20

18

10


The number of descending order 20

18

12

10

4

 

 

Reverse for reverse the letter or number sort for sort the ascending order

 

 

MULTI THREADING

 

using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks; using System.Threading;

namespace ConsoleApplicationThread

 

{

class Program

{

static void funcloop()

{

for(int i=11;i<20;i++)


{

Console.WriteLine(i);

}

}

static void Main(string[] args)

{

ThreadStart childthread = new ThreadStart(funcloop); Thread obj = new Thread(childthread);

obj.Start();

{

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

{

Console.WriteLine(i);

}

}

Console.ReadKey();

}

}

}

 

o/p 0

1

2

3

11

12

13


14

15

16

17

18

19

4

5

6

7

8

9

 

Output can be changed because of the 2 for loop working at the same time,so we can't predict the output, 2 loop are clashed

 

Thread sleep

 

 

using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks; using System.Threading;

 

namespace ConsoleApplicationthreadsleep

{


class Program

{

static void function()

{

for(int i=11;i<20;i++)

{

Console.WriteLine(i);

}

}

static void Main(string[] args)

{

ThreadStart childhead = new ThreadStart(function); Thread obj = new Thread(childhead);

obj.Start(); Thread.Sleep(2000); for(int i=0;i<10;i++)

{

Console.WriteLine(i);

}

Console.ReadKey();

}

}

}

o/p

 

11

12

13


14

15

16

17

18

19

After 200 ms

0

1

2

3

4

5

6

7

8

9

XML Serialization

XML ->extensible markup language

 

using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks; using System.Xml.Serialization;

 

namespace ConsoleApplicationxmlserialaization


{

public class person

{

public string name; public string location; public int age;

}

 

class Program

{

 

static void Main(string[] args)

{

person p = new person(); p.name = "Anzi"; p.location = "Kollam"; p.age = 32;

XmlSerializer x = new XmlSerializer(p.GetType()); x.Serialize(Console.Out, p);

Console.ReadKey();

}

}

}

 

o/p

<?xml version="1.0" encoding="DOS-720"?>


<person

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">

<name>Anzi</name>

<location>Kollam</location>

<age>32</age>

</person>

 

Jagged Array using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace ConsoleApplicationjaggedarray

{

class Program

{

static void Main(string[] args)

{

//Declare jagged array

int[][] jaggedarray = new int[3][];

//initialoze the elements of jagged array jaggedarray[0] = new int[] { 1, 2, 3 };

jaggedarray[1] = new int[] { 4, 5, 6, 7 };


jaggedarray[2] = new int[] { 8, 9 };

//Accesing elements in the jagged array for(int i=0;i<jaggedarray.Length;i++)

{

Console.WriteLine(); Console.Write("Elements[{0}]", i); for(int j=0;j<jaggedarray[i].Length;j++)

{

Console.Write("{0}", jaggedarray[i][j]);

}

}

Console.ReadKey();

 

}

}

}

 

 

 

o/p

 

Elements[0]123 Elements[1]4567 Elements[2]89

 

 

C# methods /Functions


A method is a block of code which only runs when it is called

.you can pass data ,known as parameters into a method.Methods are used to perform certain actions and they are also known as function ,reusable

using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace ConsoleApplicationfunctions

{

class Program

{

static void mymethod()

{

Console.WriteLine("i just not executed");

}

static void Main(string[] args)

{

mymethod(); mymethod(); mymethod(); Console.ReadKey();

}

 

}


}

 

o/p

i just not executed i just not executed i just not executed

 

 

 

 

 

 

 

 

 

 

 

 

 

OOPS

1.Class 2.object

3.Encapsulation 4.Abstraction 4.Inheritance 5.polymorphism


1.  class

 

Class is a blueprint of a program.class is a group of similar objects .class is a key to bind data describing on entity and associated functions together.the keyword class is used to create a class.

 

Syntax

Class classname

{

Variable declaration; Function declarations;

}

 

 

 

 

2.  Object

Object is an identifier entity that have some characteristics and behaviour

 

Syntax

Classname objectname=new classneme(); Example


using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace ConsoleApplicationoops

{

public class oopsexamples

{

public   string color = "Red";

}

class Program

{

static void Main(string[] args)

{

oopsexamples myovj = new oopsexamples(); Console.WriteLine(myovj.color); Console.ReadKey();

}

}

}

 

o/p


Red Example

using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace ConsoleApplicationoops

{

 

class Program

{

int a, b, c;

static void Main(string[] args)

{

Program myovj = new Program(); Console.WriteLine("Enter two numbers"); myovj.a = Convert.ToInt32(Console.ReadLine()); myovj.b = Convert.ToInt32(Console.ReadLine()); myovj.c = myovj.a + myovj.b; Console.WriteLine("sum ="+myovj.c); Console.ReadKey();


}

}

}

 

o/p

Enter two numbers 3

6

sum =9

 

 

 

 

 

 

 

3.  INHERITANCE

It is the property of inheriting the properties of one class to another ;

 

Syntax

Class derivedclass:baseclass

{

//methods and fields

}

The derived class is is called child or sub class


The base class is called parent class or main class The main advantages is reusability;

Types of inheritance

 

a)  Single inheritance

A derived class that inherit from only one base class

 

 

A->   Super class

B->Sub class

 

 


Example using System;

using System.Collections.Generic;


using System.Linq; using System.Text;

using System.Threading.Tasks;

 

namespace ConsoleApplicationinheritence

{

//super class class Animal

{

public void eat()

{

Console.WriteLine("This animal eats food.");

}

}

// Subclass

class Dog : Animal

{

public void bark()

{

Console.WriteLine("The dog barks.");

}

}

class Program

{

static void Main(string[] args)


{

Dog labrador = new Dog();

labrador.eat(); // Inherited method from Animal labrador.bark(); // Method from Dog Console.ReadKey();

}

}

}

o/p

This animal eats food. The dog barks.

 

b)  Hierarchical inheritance

 

A parent class and multiple child class is .

 

Hierarchical inheritance is a type of inheritance in Java where a single parent class (base class) is extended by multiple child classes (subclasses). Each child class inherits the properties and methods of the parent class independently, allowing for code reuse and logical organization.

Key Features

            Single Parent, Multiple Children: One parent class is shared among multiple child classes.

            Code Reusability: Common functionality is defined in the parent class, reducing redundancy.

            Independent Behavior: Each child class can have its own unique methods and properties in addition to the inherited ones.

 

Example


using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace ConsoleApplicationinheritence

{

//super class class Animal

{

public void eat()

{

Console.WriteLine("This animal eats food.");

}

}

// Subclass

class Dog : Animal

{

public void bark()

{

Console.WriteLine("The dog barks.");

}

}

// Child Class 2


class Cat : Animal

{

public void meow() { Console.WriteLine("The cat meows.");

}

}

 

class Program

{

static void Main(string[] args)

{

Dog labrador = new Dog();

labrador.eat(); // Inherited method from Animal labrador.bark(); // Method from Dog

Cat cat = new Cat();

cat.eat(); // Inherited from Animal cat.meow(); // Specific to Cat Console.ReadKey();

}

}

}

 

o/p

This animal eats food. The dog barks.


This animal eats food. The cat meows.

 

 


 

 

 

MULTILEVEL INHERITANCE

 

Multilevel inheritance is a type of inheritance in Java where a class inherits from a class that itself inherits from another class. This forms a chain of inheritance, allowing properties and methods to be passed down through multiple levels of classes.

Key Points

            It enables reusability of code across multiple levels.

            Each child class inherits properties and methods from its immediate parent and all ancestor classes.

            Java supports multilevel inheritance, but it does not support multiple inheritance with classes (to avoid ambiguity).

 

Example

 

using System;

using System.Collections.Generic;


using System.Linq; using System.Text;

using System.Threading.Tasks;

 

namespace ConsoleApplicationinheritence

{

//super class class Animal

{

public void eat()

{

Console.WriteLine("This mammal walks.");

}

}

// Subclass

class Mammal : Animal

{

public void walk()

{

Console.WriteLine("The dog barks.");

}

}

// Child Class 2 class Dog : Mammal


{

public void bark()

{

Console.WriteLine("The dog barks.");

}

}

 

class Program

{

static void Main(string[] args)

{

Dog dog = new Dog();

 

// Accessing methods from all levels of inheritance dog.eat();       // From Animal class

dog.walk(); // From Mammal class dog.bark(); // From Dog class Console.ReadKey();

}

}

}

 

o/p

This mammal walks. The dog barks.


The dog barks.

 

Hierarchical inheritance

 

When more than one classes inherit a same class then this is called hierarchical inheritance. For example class B, C and D extends a same class A. Lets see the diagram representation of this:

 

 

 

 

 

 

 

 

 

 

 

Hierarchical Inheritance

 

 

As you can see in the above diagram that when a class has more than one child classes (sub classes) or in other words more than one child classes have the same parent class then this type of inheritance is known as hierarchical inheritance.

 

Example

using System;


using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace ConsoleApplicationhirarchicalinheritance

{

class employee

{

public void salary()

{

Console.WriteLine(20000);

}

}

class Designer :employee

{

public void Develop()

 

{

Console.WriteLine("Designing");

}

}

class Tester :employee

{

public void Test()

{

Console.WriteLine("Testing");

}

}

class Developer : employee


{

public void Develop()

{

Console.WriteLine("Developer");

}

}

class Program

{

static void Main(string[] args)

{

Designer obj = new Designer(); obj.Develop();

obj.salary();

Developer obj1 = new Developer(); obj1.Develop();

obj1.salary();

Tester obj2 = new Tester(); obj2.Test();

obj2.salary(); Console.ReadKey();

}

}

}

 

Output Designing 20000

Developer 20000

Testing


20000

 

HYBRID INHERITANCE

 

Hybrid inheritance is a combination of two or more types of inheritance, such as single, multilevel, hierarchical, or multiple inheritance. It is used to model complex relationships between classes. However, Java does not support hybrid inheritance directly through classes because it avoids the ambiguity caused by the Diamond Problem. Instead, hybrid inheritance can be achieved in Java using interfaces.

Key Concepts

            Diamond Problem: This occurs when a class inherits from two classes that have a common base class, leading to ambiguity about which method or property to inherit. Java avoids this by not supporting multiple inheritance with classes.

            Solution with Interfaces: Java allows multiple inheritance through interfaces, as interfaces do not store implementation, only declarations.

 

Example

using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace ConsoleApplicationhirarchicalinheritance

{

class employee

{

public void salary()

{

Console.WriteLine(20000);

}

}


class Designer :employee

{

public void Design()

 

{

Console.WriteLine("Designing");

}

}

class jDesigner : Designer

{

public void jDesigne()

 

{

Console.WriteLine("Designing");

}

}

class Tester :employee

{

public void Test()

{

Console.WriteLine("Testing");

}

}

class jTester : Tester

{

public void jTest()

{

Console.WriteLine("Testing");

}

}


class Developer : employee

{

public void Develop()

{

Console.WriteLine("Developer");

}

}

class jDeveloper : Developer

{

public void jDevelope()

{

Console.WriteLine("Developing");

}

}

class Program

{

static void Main(string[] args)

{

jDesigner obj = new jDesigner(); obj.jDesigne();

obj.Design();

obj.salary();

jDeveloper obj1 = new jDeveloper(); obj1.jDevelope();

obj1.Develop(); obj1.salary();

jTester obj2 = new jTester(); obj2.Test();

obj2.Test(); obj2.salary();


Console.ReadKey();

}

}

}

 

O/P

 

Designing Designing 20000

Developing Developer 20000

Testing Testing 20000

ABSTRACTION

Abstraction is a concept of simplifying a real world object into its essential features without including background details

 

Abstract class

 

          An abstract class is declared with the help of abstract keyword.

          In c# you are not allowed to create objects of the abstract class or in other words,you cannot use the abstract class directly with the new operator.

          Class that contains the abstract keyword with some of methods(not all abstract method) is known as abstract base class

          Class that contains the abstract keyword with all of its method is known as pure abstract class.


          You are not allowed to declare the abstract methods outside the abstract class.

          You are not allowed to declare abstract class as sealed class.

 

SEALED CLASS

Its used to restricted the inheritance features of oops .once a class defined as a sealed class,this class cannot be inherited.in C#,The sealed modifier is used to declare a class sealed.

The sealed keyword word used in before class,

 

Example using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace ConsoleApplicationabstractclass

{

abstract class Animal

{

//abstract methods doesnot have body public abstract void animalsound();

//Regular method public void sleep()

{

Console.WriteLine("zzzz");

}

}

//Derived class (inherit from animal)


class pig : Animal

{

public override void animalsound()

{

//body

Console.WriteLine("The pig say we weee");

}

}

class Program

{

 

static void Main(string[] args)

{

pig mypig = new pig(); mypig.animalsound(); mypig.sleep(); Console.ReadKey();

}

}

}

Output

The pig say we weee zzzz

 

ENCAPSULATION

 

Wrapping up of data into a single unit known as encapsulation Different types of acces specifiers in c#:


c# support 6 types of access specifiers they are as follows

 

1.private 2.public 3.protected 4.internal

5. protected internal

6. private protected

 

Private

Member can be accessed within the class only\ example

Namespace privateexamp

{

Public class ABC

{

Private int id;

}

Class program

{

Static void main(string[] args)

{

ABC abc=new ABC(); abc.id=10; console.ReadKey();

}

}

}

 

ABC.id inaccessible due to its protected level


Public

 

As the name says member can be accessed from any class and any assembles

 

Example using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace ConsoleApplicationpublic

{

public class ABC

{

public int id;

}

 

class Program

{

 

static void Main(string[] args)

{

ABC abc = new ABC(); abc.id = 10;

Console.WriteLine("ID =" + abc.id); Console.ReadKey();


}

}

}

 

Output ID =10

 

 

 

PROTECTED

 

Member can be accessed within their class and derived of the same assembly

 

Example using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace ConsoleApplicationpublic

{

public class ABC

{

protected int id;

}

class childclass:ABC

{

public void print()


{

id = 10; Console.WriteLine(id);

}

}

class Program

{

 

static void Main(string[] args)

{

childclass obj = new childclass(); obj.print();

Console.ReadKey();

 

}

}

}

Output 10

 

Internal

 

Members can be accessed from anywhere within the same assembly.

Protected internal

 

Member can be accessed anywhere in the same assembly and also accessible by inheriting that class.


POLYMORPHISM

 

 

Types of polymorphism

1. static polymorphism/compile time polymorphism/Early binding

2. Dynamic polymorphism/Runtime polymorphism/Latebinding

1.  Compile-Time Polymorphism

The mechanism of linking a function with an object during compile time is called early binding it is also static binding.

a) Function Overloading: Multiple functions with the same name but different parameter lists.

b) Operator Overloading: Redefining the behavior of operators for user-defined types.

Function overloading using System;

using System.Collections.Generic;

using System.Linq; using System.Text;

using System.Threading.Tasks; using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace ConsoleApplicationarea

{

class TestData


{

public double area(double a)

{

return a * 3.14;

}

public int area(int a, int b)

{

return a * b;

}

public int area(int a, int b,int c)

{

return a * b *c;

}

}

class Program

{

static void Main(string[] args)

{

TestData obj = new TestData(); double area1 = obj.area(3);

int area2 = obj.area(5, 6); int area3 = obj.area(3,4,5);

Console.WriteLine("Area of circle =" + area1) ; Console.WriteLine("Area of Rectangle =" + area2);

 

Console.WriteLine("volume of Rectangle =" + area3); Console.ReadKey();

}

}

}


 

Output

 

Area of circle =9.42 Area of Rectangle =30 volume of Rectangle =60

 

 

2.  Run-Time Polymorphism

This type of polymorphism is resolved during the execution of the program. It is achieved through:

           Function Overriding: A derived class provides a specific implementation of a function already defined in its base class.

 

Example using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace ConsoleApplicationoperatoroverloading

{

 

class baseclass

{

// virtual

public virtual void show()

{


Console.WriteLine("Base class");

}

}

class derivedclass : baseclass

{

//Override here

public override void show()

{

Console.WriteLine("Derived class");

}

}

class Program

{

static void Main(string[] args)

{

baseclass obj;

obj = new baseclass(); obj.show();

obj = new derivedclass(); obj.show(); Console.ReadKey();

}

}

}

 

O/P

Base class Derived class


INTERFACE

An interface in Java is a blueprint for a class that defines a set of methods that a class must implement. It is a way to achieve abstraction and multiple inheritance in Java. Interfaces are widely used to define contracts or behaviors that implementing classes must adhere to.

Key Features of Interfaces

      Abstract Methods: All methods in an interface are implicitly public and abstract (until Java 8).

      Default and Static Methods: From Java 8 onwards, interfaces can have default and static methods with implementations.

      Constants: Variables in an interface are implicitly public, static, and final.

      Multiple Inheritance: A class can implement multiple interfaces, allowing Java to support multiple inheritance indirectly.

      Loose Coupling: Interfaces promote loose coupling by focusing on behavior rather than implementation.

 

In C# an interface can be defined using the interface keyword .An interface can contain declaration of methods properties indeaers and events.

 

     Interfaces specify what a class must do and not how.

     Interface cant have private members

     By default all the members of interface are public and abstract

     Using interface keyword

     Interface cannot contain fields because they represent a particular implementation of data.

     Multiple inheritance is possible with the help of interface but not with classes.

Syntax for interface Interface <interfacename>

{


//declare events

//Declare indexes

//Declare methods

//declare properties

}

Syntax for implementing interface Class classname:interfacename

 

 

Example

using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace ConsoleApplicationinterface

{

 

interface myinterface

{

void Display();

}

interface myinterface1

{

void show();

}

class myclass:myinterface,myinterface1

{

public void Display()


{

Console.WriteLine("Hello");

}

public void show()

{

Console.WriteLine("Hai");

}

}

class Program :myclass

{

static void Main(string[] args)

{

 

Program p = new Program(); p.Display();

p.show(); Console.ReadKey();

}

}

}

 

Output Hello Hai

 

Ex

using System;

using System.Collections.Generic; using System.Linq;

using System.Text;


using System.Threading.Tasks;

 

namespace ConsoleApplicationinter

{

interface Animal1

{

void animalsound();

 

}

class pig :Animal1

{

public void animalsound()

{

Console.WriteLine("The pig Sound :we wee");

}

}

class Program :pig

{

static void Main(string[] args)

{

Program p = new Program(); p.animalsound(); Console.ReadKey();

}

}

}

O/P :- The pig Sound :we wee


Base keyword

 

The ‘base’ keyword ,the derived class is able to access the method .A virtual method is a method that can be redefined in derived classes. A virtual method has an implementation in a base class as well as a derived class.

The keyword base is used to access members of the base class (the parent class) from within a derived (child) class.

It is mainly used for:Calling the base class constructor. Accessing base class methods, properties, or fields that are hidden or overridden in the derived class.

 

Example

using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace ConsoleApplicationvirtual

{

 

 

class Animal

{

public string Name;

public Animal(string name)

{

Name = name;


Console.WriteLine("Animal Constructor called");

}

}

 

class Dog : Animal

{

public Dog(string name):base(name)

 

{

Console.WriteLine("The dog constructor called.");

}

}

 

class Program

{

static void Main()

{

Dog d = new Dog("Buddy"); Console.WriteLine($"Dog's name :{d.Name}"); Console.ReadKey();

}

}

 

}

 Output

Animal Constructor called The dog constructor called. Dog's name :Buddy


The virtual keyword is used for generating a virtual path for its derived classes on implementing method over riding .The virtual keyword is used within a set with an over ride keyword.

Override keyword key word is used in the derived class of the baseclass in order to override the base class method

.The override method is used with the virtual keyword

 

Example

using System;

 

class Animal

{

// Virtual method in the base class public virtual void Speak()

{

Console.WriteLine("The animal makes a sound.");

}

}

 

class Dog : Animal

{

// Overriding the virtual method in the derived class public override void Speak()

{

Console.WriteLine("The dog barks.");

}

}


class Program

{

static void Main()

{

Animal myAnimal = new Animal();

myAnimal.Speak(); // Output: The animal makes a sound.

 

Animal myDog = new Dog(); myDog.Speak(); // Output: The dog barks.

}

}

 

 

            virtual: The Speak method in the Animal class is marked as virtual, allowing it to be overridden in derived classes.

            override: The Speak method in the Dog class uses the override keyword to provide a new implementation for the base class's Speak method.

 

CONSTRUCTOR

          Constructor is a member function that invoke automatically when the object is created.

          Constructor of a class must have the same name as the class name in which it resides.

          A Constructor can not be abstract, final, static and Synchronized

          Within a class, you can create only one static constructor.

          A constructor doesn't have any return type, not even void.

              A static constructor cannot be a parameterized constructor.

              A class can have any number of constructors.

          Access modifiers can be cued in constructor declaration to control its access ie, which other class can call the constructor


 

 

Types of constructors

 

a)   Default constructor: Constructor with no parameters is called default constructor.

b)   Parameterized  constructor:  Constructor with parameters called parameterized Constructor .

 

Example

using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace ConsoleApplicationconstructor

{

class myconstructor

{

public int a, b;

public myconstructor(int x,int y)

{

a = x;

b = y;

}

public myconstructor()//default constructor

{

a = 200;


b = 275;

}

}

class Program

{

static void Main(string[] args)

{

myconstructor v = new myconstructor(100, 175); Console.WriteLine("value of a=" + v.a); Console.WriteLine("value of b=" + v.b); myconstructor v1 = new myconstructor(); Console.WriteLine(v1.a); Console.WriteLine(v1.b);

 

Console.ReadKey();

 

}

}

}

 

Output

value of a=100 value of b=175 200

275

DISTRUCTOR

 

Distructor is a member function that invoke automatically when  the object         is   destroyed.  A            distructor      works               opposite          to


constructor,its destruct the objects of classes. It can be defined only once in a class.

 

characteristics of distructor

 

*    In c#, distructor can be used only in classes and a class can contain only one distructor.

 

*   the distructor in class can be represented by using tilde (~) operator.

 

*   The distructor in c# won't accept any parameters and access modifiers.

 

*The distructor will invoke automatically, whenever on instance of a class is no longer needed.

 

 

 

*      The distructor automatically invoked by garbage collector (GC) whenever the class object that are no longer needed in the application.

 

*   A distructor is a unique to its class is, there cannot be more than one distructor in a class

 

*   It cannot be defured in Structure. It is only used wit classes.

*   It cannot be overloaded or inherited.

*   it is called when the program exit.

*   internally ,destructor called the finalized method on the base class of object

 

Example


using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace ConsoleApplication4distructor

{

class user

{

public user()

{

Console.WriteLine("As instance of class created");

 

}

~user()

{

Console.WriteLine("As instance of class distroyed");

 

}

}

class Program

{

static void Main(string[] args)

{

Details(); GC.Collect(); Console.ReadLine();

 

}


public static void Details()

{

user us = new user(); Console.ReadKey();

 

}

}

}

Output

As instance of class created As instance of class distroyed

Named and Optional parameters Named parameter:-

Named parameter allow developers to pass a method arguments

with parameter names.This features allows us to associated argument name its value at the time of function calling.

When we make named arguments ,the arguments are evaluated in the order in which they are passed.

It helps us,not to remember the order of parameters,if we know the parameters name we can pass that in any order.

 

Example using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;


namespace ConsoleApplication4named

{

class Program

{

public string GetFullname(string strFirstName,string strLastName)

{

return strFirstName + " " + strLastName;

}

static void Main(string[] args)

{

Program objpgm = new Program();

  string strFullname = objpgm.GetFullname("Anjana", "Anil");

 string   strFullname1  =              objpgm.GetFullname(strFirstName:"Anjana", strLastName: "Anil");

    string strFullname2 = objpgm.GetFullname(strLastName : "Anil", strFirstName: "Anjana");

Console.WriteLine(strFullname); Console.WriteLine(strFullname1); Console.WriteLine(strFullname2); Console.ReadKey();

}

}

}

 

output Anjana Anil Anjana Anil Anjana Anil


Optional parameters

The optional parameters contains a default value in function.

It we do not pass optional argument value at calling time ,the default value is used.

It helps to executed arguments for some parameters.

 

Example using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace ConsoleApplicationoptional

{

class Program

{

public  void  scholoar(string  strfname,string                                 strlname,int iage=20,string strbranch="ComputerScience")

{

Console.WriteLine("First Name : {0}", strfname); Console.WriteLine("Last Name : {0}", strlname); Console.WriteLine("Age : {0}", iage); Console.WriteLine("Branch: {0}", strbranch);

}

static void Main(string[] args)

{

Program p = new Program(); p.scholoar("Anjana", "Anil");

p.scholoar("Anzi", "Beegum", 30);


p.scholoar("Diya", "krishna", 27, "information Technolgy"); Console.ReadKey();

}

}

}

 

Output

First Name : Anjana Last Name : Anil Age : 20

Branch: ComputerScience First Name : Anzi

Last Name : Beegum Age : 30

Branch: ComputerScience First Name : Diya

Last Name : krishna Age : 27

Branch: information Technolgy

 

Value Types and Reference Type [call by value and call by reference] Value type:

 

A data type is called a value type if it stores its data directly in its own memory space. This means the variable contains the actual value, not a reference to the value.

 

-   All value types derive from System.ValueType.


-     Value types are usually stored on the stack (though the exact memory location depends on how they are used).

-       When you create a value type variable, memory is directly allocated to store the value.

 

Examples of value types in C#:

-   int

-   float

-   char

-   bool

-   struct

-   enum Example:

int a = 10;

int b = a; // b holds a copy of the value 10

 

 

In the above, a and b are independent; changing one won’t affect the other

Reference type

In programming, especially in C#, a reference type is a type that stores a reference (address) to the memory location where the actual data is held. This means multiple variables can refer to the same object in memory.

 

Examples of Reference Types:


-   Class

-   Array

-   String

-   Interface

-   Delegate

-   Object

 

Example in C#: csharp

class Person {

public string Name;

}

 

Person p1 = new Person(); p1.Name = "Alice";

 

Person p2 = p1; p2.Name = "Bob";

 

Console.WriteLine(p1.Name); // Output: Bob (because p1 and p2 point to the same object)

 

Example using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;


namespace ConsoleApplicationReferncetype

{

class person

{

public int age;

}

class Program

{

static void square(person a,person b)

{

a.age = a.age * a.age; b.age = b.age * b.age;

Console.WriteLine(a.age + " " + b.age);

}

static void Main(string[] args)

{

person p1 = new person(); person p2 = new person(); p1.age = 5;

p2.age = 10;

Console.WriteLine(p1.age + " " + p2.age); square(p1, p2);

Console.WriteLine(p1.age + " " + p2.age); Console.WriteLine("pass any key to exit"); Console.ReadKey();

}

}


}

Output 5 10

25 100

25 100

pass any key to exit

 

Delegate

In C#, a delegate is a type-safe function pointer it holds a reference to a method with a specific signature and return type.

A delegate is a reference type variable that holds the reference to a method. This reference can be changed at runtime.

 

A delegate can be declared using the delegate keyword.

 

Delegates are one of the main built-in types in .NET. A delegate is a class, which is used to create and invoke methods at runtime

 

Syntax:

csharp

delegate returnType DelegateName(parameterList);

 

 

Example:

csharp

// Define a delegate

delegate void Greet(string name);


// Method matching the delegate signature void SayHello(string name) {

Console.WriteLine("Hello " + name);

}

 

// Use the delegate Greet greet = SayHello;

greet("John"); // Output: Hello John

 

 

Key Points:

-   Delegates can point to static or instance methods.

-   You can use them to pass methods as parameters.

-   Multicast delegates allow combining multiple methods.

-   Events in C# are built on delegates. Why use delegates?

 

In    many   scenarios,    programmers    need    to    pass       methods                  as parameters to other methods. For this purpose, delegates are used.

 

Example using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks; namespace ConsoleApplication4Delegate


{

delegate int calculate(int n); class Program

{

static int number = 100; public static int add(int n)

{

number=(number + n); return number;

}

public static int mul(int n)

{

number= number * n; return number;

}

public static int getNumber()

{

return number;

}

static void Main(string[] args)

{

calculate c1 = new calculate(add); calculate c2 = new calculate(mul); c1(20);

Console.WriteLine("After c1 delegate ,Number is :" + getNumber());

c2(3);


Console.WriteLine("After c2 delegate ,Number is :" + getNumber());

Console.ReadKey();

 

}

}

}

 

Output

After c1 delegate ,Number is :120 After c2 delegate ,Number is :360

 

 

 

Name space

          It is a collection of names where is each name is unique

          They form of logical boundary for a group of classes

          Name space must be specified in protect properties

ASSEMBLY

                     It is an output unit

          It is a unit of deployment and unit of version

          Assemblies contain MSIL code.

          Assemblies                            are                                             self Describing{eg:metaData,manifest}

          It is the primary building block of a .Net framework application


          It is a collection of functionality that is built versioned and delayed as a single implementation unit(as one or more files)

          All managed types and resources are marked either as accessible only with in their implementation unit,or by code outside that unit.

//dll files or exe files.. Already build and reference them in to the project

 

 

Namespace:

-     A namespace is a container for classes, interfaces, structs,

enums, and delegates.

-   It is used to organize code and avoid name conflicts.

-   Think of it like a folder structure in your project.

 

Example:

csharp

namespace MyProject.Utilities { class Calculator {

// code

}

}

 

 

---


Assembly:

-    An assembly is a compiled code library used for deployment,

versioning, and security.

-   It is a .dll or .exe file that contains compiled C# code.

-   Assemblies can have one or more namespaces inside them.

| Feature           | Namespace                                     | Assembly

|

|----------------|--------------------------------------|----------------------

------------- |

| Definition     | Logical group of related classes     | Physical unit of compiled code                              |

| Type           | Logical (used during coding)         | Physical (used during execution)                         |

| File type        | No file created                         | .dll or .exe file

|

| Purpose         | Organize code                           | Deploy and run application

 

Example using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace ConsoleApplicationnamespaces

{


namespace first

{

class namespace_C1

{

public void fun()

{

Console.WriteLine("My First namespace");

}

}

}

namespace second

{

class namespace_C2

{

public void fun()

{

Console.WriteLine("My second namespace");

}

}

}

class Program

{

static void Main(string[] args)

{

first.namespace_C1 f1 = new first.namespace_C1();

second.namespace_C2    f2                                     =                                     new

second.namespace_C2();


f1.fun();

f2.fun(); Console.ReadKey();

 

}

}

}

 

Output

My First namespace My second namespace

 

Class Library

Its Globalvalues class in ayurlive i have done in touchq

File->New ->project->SearchClassLibrary and select write claa name->ok

// ClassLibrary1.h #pragma once

using namespace System; namespace ClassLibrary1 {

public ref class Class1

{

public: int fun()


{

return 10;

}

// TODO: Add your methods for this class here.

};

}

 

Its only build not have output

 

File->new ->project->console.FrameWork->ok->create solution explore

Refrences->add reference->browse->click

Class path of class (ClassLibrary1 )->Debug->dll file ->select the file->ok

 

using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace ConsoleApplicationAsd

{

class Program

{

static void Main(string[] args)

{


ClassLibrary1.Class1   new1                                   =                                   new

ClassLibrary1.Class1();

int i = new1.fun();

Console.WriteLine("The number of function is " + i); Console.ReadKey();

}

}

}

 

Output

The number of function is 10

Exception

Exception is an abnormal situation Exception handling

To handle the exception situation C# use the following keywords Keyword

 

Key Word

Definition

try

Used to define a try block.This Block holds the code that my thrown an exception

catch

Used to define a catch blocks.the block catches the exception throw by the try block

finally

The block holds the default code

throw

Throw an exception manually


Syntax Try

{

}

catch()

{

}

Finally

{

Default code

}

 

1.  Divided by zero Exception

using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace ConsoleApplicationException

{

class Program

{

static void Main(string[] args)

{

try

{

int a = 10;


int b = 0; int x = a / b;

}

catch(Exception ex)

{

Console.WriteLine(ex);

}

 

Console.WriteLine("Rest of the code"); Console.ReadKey();

}

}

}

 

Output

 

System.DivideByZeroException: Attempted to divide by zero.

at ConsoleApplicationException.Program.Main(String[] args) in D:\ayurlive-windows\BanquetManagement\ConsoleApplicationExc eption\ConsoleApplicationException\Program.cs:line 17

Rest of the code

2.  Index out of Range exception

 

a)     stringindexoutofRangeException

b)  ArrayIndexoutofRangeException


StringIndexOutOfRangeException using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace ConsoleApplicationException

{

class Program

{

static void Main(string[] args)

{

string Example = "Hello World"; try

{

char outboundchar= Example[20];

}

catch(Exception ex)

{

Console.WriteLine("Caugn an exception "+ ex); Console.ReadKey();

}

 

 

}

}


}

Output

Caught an exception System.IndexOutOfRangeException: Index was outside the bounds of the array.

at System.String.get_Chars(Int32 index)

at ConsoleApplicationException.Program.Main(String[] args)                                                                         in

D:\ayurlive-windows\BanquetManagement\ConsoleApplic ationException\ConsoleApplicationException\Program.cs:l ine 16

ArrayIndexOutofRangeException

using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace ConsoleApplicationException

{

class Program

{

static void Main(string[] args)

{

string[] color = { "Blue", "Green", "Red" }; try

{

Console.WriteLine(color[5]);


}

catch(Exception ex)

{

Console.WriteLine(" exception occures "+ ex); Console.ReadKey();

}

 

 

}

}

}

 

 

exception occures System.IndexOutOfRangeException: Index was outside the bounds of the array.

at ConsoleApplicationException.Program.Main(String[] args)                                                                         in

D:\ayurlive-windows\BanquetManagement\ConsoleApplic ationException\ConsoleApplicationException\Program.cs:l ine 16

 

3.  FileNotFoundException using System;

using System.Collections.Generic; using System.IO;

using System.Linq; using System.Text;


using System.Threading.Tasks;

 

namespace ConsoleApplicationException

{

class Program

{

static void Main(string[] args)

{

try

{

using (StreamReader reader = new

StreamReader("textMatrix.txt"))

{

Console.WriteLine(reader.ReadToEnd());

}

}

catch(Exception ex)

{

Console.WriteLine( ex); Console.ReadKey();

}

Console.ReadKey();

 

}

}

}


 

System.IO.FileNotFoundException: Could not find file 'D:\ayurlive-windows\BanquetManagement\ConsoleApplic ationException\ConsoleApplicationException\bin\Debug\te xtMatrix.txt'.

File                                                                      name:

'D:\ayurlive-windows\BanquetManagement\ConsoleApplic ationException\ConsoleApplicationException\bin\Debug\te xtMatrix.txt'

at System.IO. Error.WinIOError(Int32 errorCode, String maybeFullPath)

at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)

at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)

at System.IO.StreamReader..ctor(String path, Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize, Boolean checkHost)

at System.IO.StreamReader..ctor(String path)


at ConsoleApplicationException.Program.Main(String[] args)                                                                         in

D:\ayurlive-windows\BanquetManagement\ConsoleApplic ationException\ConsoleApplicationException\Program.cs:l ine 16

 

4.  InvalidOperationalException

 

using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace ConsoleApplicationinvalid1

{

class Program

{

 

static void Main(string[] args)

{

List<int> numbers = new List<int> { 1, 2, 3, 4, 5 }; try

{

foreach(int number in numbers)

{

if(number==3)


{

numbers.Remove(number);

}

}

}

catch(InvalidOperationException e)

{

Console.WriteLine("caught an invalid operation exception" + e.Message);

foreach(int number in numbers)

{

Console.WriteLine(number);

}

Console.ReadKey();

}

}

}

}

 

Output

caught   an    invalid   operation             exceptionCollection        was modified; enumeration operation may not execute.

1

2

4

5


C# Break

You have already seen the break statement used in an earlier chapter of this tutorial .it is used to “jump out” of switch statement.

The break statement can also be used to jump out of a loop.

using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace ConsoleApplicationbreak

{

class Program

{

static void Main(string[] args)

{

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

{

if(i==4)

{

break;

}

Console.WriteLine(i);

}

Console.ReadKey();


}

}

}

 

Output 0

1

2

3

C# continue

The continue statement breaks one iteration   (in the loop

),if a specified condition occurs and continuous with the next iteration in the loop

 

using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace ConsoleApplicationbreak

{

class Program

{

static void Main(string[] args)

{

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


{

if(i==4)

{

continue;

}

Console.WriteLine(i);

}

Console.ReadKey();

}

}

}

 

Output 0

1

2

3

5

6

7

8

9

 

Class members

Fields and method inside classes are often referred to as class members

using System;


using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace ConsoleApplicationbreak

{

class Program

{

string color = "Red"; int maxspeed = 200;

static void Main(string[] args)

{

Program obj = new Program(); Console.WriteLine(obj.color); Console.WriteLine(obj.maxspeed); Console.ReadKey();

}

}

}

Output Red 200


Extension method

Extension methods in c# allow you to add new methods to existing type without modifying the original type or creating a new divided type.They are defined as stattic methods in stattic classes and the first parameter of the method specifies the type that the methods operates on proceed by the this keyword.

using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace ConsoleApplicationbreak

{

public static class extensionmethos

{


 

value)

{


public static string UppercaseFirstletter(this string

 

 

if (value.Length > 0)

{


char[] array = value.ToCharArray(); array[0] = char.ToUpper(array[0]); return new string(array);

}

return value;


}

}

public class Program {

static void Main(string[] args)

{

string value = "dotnet";

value = value.UppercaseFirstletter(); Console.WriteLine(value); Console.ReadKey();

}

}

}

 

Output Dotnet

1) Pgm to check reverse a number using System;

using System.Collections.Generic;

using System.Linq; using System.Text;

using System.Threading.Tasks;

 

namespace ConsoleApplicationbreak

{


public class Program {

static void Main(string[] args)

{

 

Console.WriteLine("Enter a number");

int n = Convert.ToInt32(Console.ReadLine()); int d = 0;

d = n; int z=0;

while(d%10>1)

{

z = d % 10;

Console.Write(z); d = (n - z) / 10;

n = d;

}

Console.ReadKey();

}

}

}

 

 

 

Output

Enter a number 2345

5432


Planidrome using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace ConsoleApplicationbreak

{

 

public class Program {

static void Main(string[] args)

{

 

Console.WriteLine("Enter a number");

int     number         =

Convert.ToInt32(Console.ReadLine()); int originalnumber = number; int reversenumber = 0;

int tempnumber=number; while(number>0)

{

int digit = number % 10;

reversenumber = reversenumber * 10 + digit; number /= 10;

}

Console.WriteLine(reversenumber);


if(tempnumber==reversenumber)

{

Console.WriteLine("The number is palindrome");

}


else

{

 

palindrome");

}


 

Console.WriteLine("The number is not


Console.ReadKey();

}

}

}

 

Output

Enter a number 232

232

The number is palindrome

No comments:

Post a Comment

Techzmatrix