C#

 

               C#

C# (pronounced "See Sharp") is a modern, object-oriented, and type-safe programming language. 

Several C# features help create robust and durable applications.

 Garbage collection automatically reclaims memory occupied by unreachable unused objects.

 Nullable types guard against variables that don't refer to allocated objects.

 Exception handling provides a structured and extensible approach to error detection and recovery.

 Lambda expressions support functional programming techniques. 

Language Integrated Query (LINQ) syntax creates a common pattern for working with data from any source.

 Language support for asynchronous operations provides syntax for building distributed systems.

 C# has a unified type system. All C# types, including primitive types such as int and double, inherit from a single root object type. All types share a set of common operations. Values of any type can be stored, transported, and operated upon in a consistent manner.

C#- My first Code-

using System;

class Program

{

    static void Main(String[] args)

    {

        Console.WriteLine("Hii Sudhanshu");

    }

}

 using directive that references the System namespace. Namespaces provide a hierarchical means of organizing C# programs and libraries. Namespaces contain types and other namespaces

—for example

 the System namespace contains a number of types, such as the Console class referenced in the program, and a number of other namespaces, such as IO and Collections.using directive that references a given namespace enables unqualified use of the types that are members of that namespace. Because of the using directive, the program can use Console.WriteLine as shorthand for System.Console.WriteLine.

 

Using System - indicates that you are using the System namespace.

-   Used to organize your code and is collection of classes, interfaces, structs, enums and delegates.

Reading & Writing to Console-

-   Reading from the console

-   Writing to the console

-   2 ways to write to console

a)    Concatenation

b)    Place holder syntax – Most preferred.

using System;

class Program

{

    static void Main(String[] args)

    {

        //Prompt the user for his name

        Console.WriteLine("Please enter your name: ");

        //Read the name from console.

        string UserName = Console.ReadLine();

        // Concatenate name with hello word and print

        Console.WriteLine("Hello"+UserName);

        // Place holder syntax - Most preferred

        Console.WriteLine("Hello {0}",UserName);

    }

}

Output:-

Please enter your name:

Sudhanshu

Hello Sudhanshu

An identifier is a variable name. An identifier is a sequence of unicode characters without any whitespace. An identifier may be a C# reserved word, if it's prefixed by @. Using a reserved word as an identifier can be useful when interacting with other languages.

Types and variables

type defines the structure and behavior of any data in C#.

Two kinds of type in c#.

1)    Value types-  simple typesenum typesstruct typesnullable value types, and tuple value types.

2)    Reference types - class typesinterface typesarray types, and delegate types

  • delegate type represents references to methods with a particular parameter list and return type. Delegates make it possible to treat methods as entities that can be assigned to variables and passed as parameters. Delegates are analogous to function types provided by functional languages. They're also similar to the concept of function pointers found in some other languages. Unlike function pointers, delegates are object-oriented and type-safe.

Built-in type in C#

Boolean, Integral, Floating, Decimal, String.

-String

using System;

class Program

{

    static void Main(String[] args)

    {

        string Name = "\"Sudhanshu\"";

        Console.WriteLine(Name);

    }

}

Output- "Sudhanshu"

Verbatim Literal

Verbatim literal, is a string with an @ symbol prefix, as in @”Hello”.

Without Verbatim literal: "C:\\Sudhanshu\\Dotnet\\Csarp" – Less Readable

With Verbatim literal: @"C:\\Sudhanshu\\Dotnet\\Csarp" – Better Readable

using System;

class Program

{

    static void Main(String[] args)

    {

        string Name = @"C:\\Sudhanshu\\Dotnet\\Csarp";

        Console.WriteLine(Name);

    }

}

Output- C:\\Sudhanshu\\Dotnet\\Csarp

Operators

-   Ternary Operator ?:

using System;

class Program

{

    static void Main(String[] args)

    {

       int num = 12;

        bool isNum12 = num==12? true:false;

        Console.WriteLine("Number == 12 is {0}",isNum12);

    }

}

Output:- Number == 12 is True

-   Null Coalescing Operator ??:

using System;

class Program

{

    static void Main(String[] args)

    {

      int? TicketOnSale = null;

        int AvailabalTickets;

        if (TicketOnSale == null)

        {

            AvailabalTickets = 0;

        }

        else

        {

            AvailabalTickets = TicketOnSale.Value;

        }

        Console.WriteLine("AvialableTickets = {0}",AvailabalTickets);

    }

}

Output:-  AvialableTickets = 0

using System;

class Program

{

    static void Main(String[] args)

    {

        int? TicketOnSale = 100;

        int? AvialableTickets = TicketOnSale ?? 0;

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

    }

}

Output- AvailableTickets = 100

Datatype conversions in C#

Float f = 123.43f;

Int i = (int)f;  or   int i = Convert.ToInt32(f);

Difference between Parse and TryParse.

Parse() – method throws an exception if it cannot parse the value, whereas TryParse() return a bool indicating whether it succeeded or failed.

Use parse() if you are sure the value will be valid , Otherwise use TryParse().

using System;

class Program

{

    static void Main(String[] args)

    {

        string str = "100";

        int i = int.Parse(str);

        Console.WriteLine(i);

    }

}

Output- 100

--

using System;

class Program

{

    static void Main(String[] args)

    {

        string str = "100TG";

        int result = 0;

        bool IsConversionSuccessful = int.TryParse(str, out result);

        if (IsConversionSuccessful)

        {

            Console.WriteLine(result);

        }

        else

        {

            Console.WriteLine("Please enter valid number");

        }

    }

}

Output- Please enter valid number

 

Arrays in C#

using System;

class Program

{

    static void Main(String[] args)

    {

        Console.WriteLine("Enter no. of elements: ");

        int i=int.Parse(Console.ReadLine());

        int[] arr = new int[i];

        Console.WriteLine("Enter arrays elements: ");

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

        {

            arr[j] = int.Parse(Console.ReadLine());

        }

        Console.WriteLine("Output is .");

        foreach(int j in arr)

        {

            Console.Write(j+" ");

        }

    }

}

Output-

Enter no. of elements:

3

Enter arrays elements:

5

7

8

Output is .

5 7 8

Comments in C#

-   Single line Comments   - //

-   Multi line Comments - /**/

-   XML Documentation Comments -///

Keyboard Shortcut-  Ctrl+C

Switch case:- example

using System;

class Program

{

 

    static void Main(String[] args)

    {

        int TotalCoffeeCost = 0;

        start:

        Console.WriteLine("1-Small, 2- Medium, 3-Large");

        int UserChoice = int.Parse(Console.ReadLine());

        switch (UserChoice)

        {

            case 1:

                TotalCoffeeCost += 1;

                break;

            case 2:

                TotalCoffeeCost += 2;

                break;

            case 3:

                TotalCoffeeCost += 3;

                break;

            default:

                Console.WriteLine("Your choice {0} is invalid", UserChoice);

                break;

 

        }

        Decide:

        Console.WriteLine("Do you want to buy another coffee - yes or no ?");

        string UserDecision = Console.ReadLine();

        switch (UserDecision)

        {

            case "yes":

                goto start;

                break;

            case "no":

                break;

            default :

                Console.WriteLine("your choice {0} is invalid. please try again....");

                goto Decide;

 

        }

        Console.WriteLine("Thank you for shopping with us");

        Console.WriteLine("Bill Amount = {0}",TotalCoffeeCost);

    }

}

Output-

1-Small, 2- Medium, 3-Large

2

Do you want to buy another coffee - yes or no ?

yes

1-Small, 2- Medium, 3-Large

3

Do you want to buy another coffee - yes or no ?

no

Thank you for shopping with us

Bill Amount = 5

 

Do while loop

using System;

class Program

{

 

    static void Main(String[] args)

    {

        string UserChoice = string.Empty;

        do

        {

            Console.WriteLine("Please enter your target?");

            int UserTarget = int.Parse(Console.ReadLine());

            int start = 0;

            while (start < UserTarget)

            {

                Console.Write(start + " ");

                start = start + 2;

            }

            do

            {

                Console.WriteLine("Do you want to continue- yes or no?");

                UserChoice = Console.ReadLine();

                if (UserChoice != "yes" && UserChoice != "no")

                {

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

                }

 

            } while (UserChoice != "yes" && UserChoice != "no");

        }while (UserChoice=="yes");

    }

}

Output-

Please enter your target?

10

0 2 4 6 8 Do you want to continue- yes or no?

yes

Please enter your target?

15

0 2 4 6 8 10 12 14 Do you want to continue- yes or no?

No

Methods

-   Methods without static

-   using System;

-   class Program

-   {

-    

-       static void Main(String[] args)

-       {

-         Program p  = new Program();

-           p.EvenNum();

-       }

-       public void EvenNum()

-       {

-           int start = 0;

-           while (start <= 20)

-           {

-               Console.Write(start+" ");

-               start= start+2;

-           }

-       }

-   }

Output- 0 2 4 6 8 10 12 14 16 18 20

-   Methods with static

using System;

class Program

{

 

    static void Main(String[] args)

    {

        Program.EvenNum();

    }

    public static void EvenNum()

    {

        int start = 0;

        while (start <= 20)

        {

            Console.Write(start+" ");

            start= start+2;

        }

    }

}

Output- 0 2 4 6 8 10 12 14 16 18 20

 

 

Different type of Method parameters

4 type of parameters –

1)  Value parameter -    Method_Name( methodType value)

2)  Reference parameter- Method_Name( ref methodType value)

3)  Out parameter-

using System;

class Program

{

 

    static void Main(String[] args)

    {

        int sum = 0, product = 0;

        Calculate(10, 20, out sum, out product);

        Console.WriteLine("sum = {0} & product = {1}", sum, product);

    }

    public static void Calculate(int a, int b,out int sum, out int product)

    {

        sum = a+b;

        product = a*b;

    }

}

Out:- sum = 30 & product = 200

4)  Parameter Arrays

using System;

class Program

{

    public static void Main()

    {

        int[] num = new int[3];

        ParamsMethod(1, 2, 3, 4, 5);

    }

    public static void ParamsMethod(int a,params int[] Num)

    {

        Console.WriteLine("There are {0} elements",Num.Length);

        foreach (int i in Num) { Console.Write(i+" "); }

    }

}

namespace-

using System;

using PATA = ProjectA.TeamA;

class Program

{

    public static void Main()

    {

        PATA.ClassA.print();

        ProjectA.TeamB.ClassB.print();

    }

}

namespace ProjectA

{

    namespace TeamA

    {

        class ClassA

        {

            public static void print()

            {

                Console.WriteLine("Team A method");

            }

        }

             

    }

}

namespace ProjectA

{

    namespace TeamB

    {

        class ClassB

        {

            public static void print()

            {

                Console.WriteLine("Team B method");

            }

        }

 

    }

}

   

Output:-

Team A method

Team B method

 

CLASS-

using System;

class Student

{

    string _firstName;

    string _lastName;

    public Student(): this("No firstName provided", " No lastName provided")

    {

 

    }

    public Student(string firstName, string lastName)

    {

        this._firstName = firstName;

        this._lastName = lastName;

    }

    public void printFullName()

    {

        Console.WriteLine("Full Name = {0}  {1}",this._firstName,this._lastName);

    }

    ~Student()

    {

        //clean up code -colled distractors

    }

}

class Program

{

   public static void Main(String[] args)

    {

        Student student = new Student();

        Student s = new Student("Sudhanshu", "Kumar");

        student.printFullName();

        s.printFullName();

    }

  

}

Output-

Full Name = No firstName provided   No lastName provided

Full Name = Sudhanshu  Kumar

 

Static & Instance class members-

using System;

class Student

{

    int id;

    string name;

    static string collage = "IEM, KOlkata";

    Student(int id, string name)

    {

        this.id = id;

        this.name = name;

    }

    public static void print()

    {

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

    }

 

}

class Program

{

   public static void Main(String[] args)

    {

       Student.print();

    }

  

}

Output-

collage = IEM, Kolkata

Enum – An enum is a spatial class that represents a group of constants ( unchangeable/read-only variables).

Ex-

class Program

{

  enum Level

  {

    Low,

    Medium,

    High

  }

  static void Main(string[] args)

  {

    Level myVar = Level.Medium;

    Console.WriteLine(myVar);

  }

}

Output- Medium

Ex2-

enum Months
{
  January,    // 0
  February,   // 1
  March,      // 2
  April,      // 3
  May,        // 4
  June,       // 5
  July        // 6
}
 
static void Main(string[] args)
{
  int myNum = (int) Months.April;
  Console.WriteLine(myNum);
}

Output- 3

 

 

Inheritance

using System;

public class Employee

{

    public string FirstName;

    public string LastName;

    public string Email;

    public void printFullNAme()

    {

        Console.WriteLine(FirstName+" "+LastName);

    }

}

public class FullTimeEmployee : Employee

{

    public float yearSalary;

}

public class PartTimeEmployee : Employee

{

    public float HourlyRate;

}

public class Program

{

    public static void Main()

    {

        FullTimeEmployee FTE = new FullTimeEmployee();

        FTE.FirstName = "Sudhanshu";

        FTE.LastName = "Kumar";

        FTE.yearSalary = 50000;

        FTE.printFullNAme();

    }

}

Output-

Sudhanshu Kumar

-   Inheritance is one of the primary pillars of OOPs .

-   It allows to code reduce.

 

using System;

public class Employee

{

    public string FirstName;

    public string LastName;

    public string Email;

    public void printFullNAme()

    {

        Console.WriteLine(FirstName+" "+LastName);

    }

}

public class FullTimeEmployee : Employees

{

    public float yearSalary;

    public new void printFullNAme()

    {

        Console.WriteLine(FirstName + " " + LastName+" ~~~~");

    }

}

public class PartTimeEmployee : Employee

{

    public float HourlyRate;

}

public class Program

{

    public static void Main()

    {

        FullTimeEmployee FTE = new FullTimeEmployee();

        FTE.FirstName = "Sudhanshu";

        FTE.LastName = "Kumar";

        FTE.yearSalary = 50000;

        FTE.printFullNAme();

    }

}

Output- Sudhanshu Kumar ~~~~

using System;

public class Employee

{

    public string FirstName;

    public string LastName;

    public string Email;

    public void printFullNAme()

    {

        Console.WriteLine(FirstName+" "+LastName);

    }

}

public class FullTimeEmployee : Employee

{

    public float yearSalary;

    public new void printFullNAme()

    {

        Console.WriteLine(FirstName + " " + LastName+" ~~~~");

    }

}

public class PartTimeEmployee : Employee

{

    public float HourlyRate;

    public new void printFullNAme()

    {

        //Console.WriteLine(FirstName + " " + LastName + " ~~~~");

        base.printFullNAme();

    }

}

public class Program

{

    public static void Main()

    {

        FullTimeEmployee FTE = new FullTimeEmployee();

        FTE.FirstName = "Sudhanshu";

        FTE.LastName = "Kumar";

        FTE.yearSalary = 50000;

        FTE.printFullNAme();

        PartTimeEmployee PTE = new PartTimeEmployee();

        PTE.FirstName = "PArt TIme";

        PTE.LastName = "Employee";

        PTE.printFullNAme();// print using base.fulprint

        ((Employee) PTE).printFullNAme();// Here we use typeCast

    }

}

Output-

Sudhanshu Kumar ~~~~

PArt TIme Employee

PArt TIme Employee 

METHOD OVERRIDING VS METHOD HIDING







Comments

Popular posts from this blog