C# Concepts and Practiced Programs

https://www.udemy.com/course/csharp-from-scratch/learn/lecture/11601952?start=705#conten


https://www.geeksforgeeks.org/private-constructors-in-c-sharp/


Private Constructor is a special instance constructor present in C# language. Basically, private constructors are used in class that contains only static members.

Important points:

It is the implementation of a singleton class pattern.
Use private constructor when class have only static members.
Using private constructor, prevents the creation of the instances of that class.
If a class contains only private constructor without parameter, then it prevents the automatic generation of default constructor.
If a class contains only private constructors and does not contain public constructor, then other classes are not allowed to create instances of that class except nested class.

class Geeks {
    // Variables
    public static string name;
    public static int num;
    // Creating private Constructor
    // using private keyword
    private Geeks() {
        Console.WriteLine("Welcome to Private Constructor");
    }
  
    // Default Constructor
    // with parameters
    public Geeks(string a, int b) {
  
        name = a;
        num = b;
    }
}
  
// Driver Class
class GFG {
  
    // Main Method
    static void Main() {
  
        // This commented line raises error because
        // the constructor is inaccessible
        // Geeks obj1 = new Geeks();
  
        // Here, the only default 
        // constructor will invoke
        Geeks obj2 = new Geeks("Ankita", 2);
  
        Console.WriteLine(Geeks.name + ", " + Geeks.num);
    }
}

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

Difference between Static Constructors and Non-Static Constructors

Static constructors are used to initialize the static members of the class and are implicitly called before the creation of the first instance of the class


Non-static constructors are used to initialize the non-static members of the class

class Geeks{
// Declaration of
// static constructor
static Geeks()
{
    Console.WriteLine("Static constructor");
}
// Declaration of
// non-static constructor
public Geeks()
{
    Console.WriteLine("Non-Static constructor");
}
// Main Method
static void Main(string[] args)
{
  
    // 1.static constructor will call implicitly
    // as soon as the class start to execute.
    // 2.the first block of code to execute
    // inside the class will be static
    // constructor only.
  
    // calling non-static constructor
    // here we are calling non-static
    // constructor twice as we are
    // creating two objects
    Geeks obj1 = new Geeks();
    Geeks obj2 = new Geeks();
}
}




class Geeks
{
static int s;
int ns;
//static Geeks(int s)
//{
//    Console.WriteLine("Static constructor");
//}
static Geeks()
{
    Console.WriteLine("Static constructor");
}
public Geeks()
{
    Console.WriteLine("Non-Static constructor");
}
// Main Method
static void Main(string[] args)
{
    // Static fields can
    // be accessed directly
    Console.WriteLine("Value of s is: " + s);
    // Calling non-static constructor
    // a static constructor must be parameterless
    //Geeks obj1 = new Geeks(4);
    Geeks obj1 = new Geeks();
    // Printing the value
    // of non-static field
    Console.WriteLine("Value of ns is: " + obj1.ns);
}
}

Explanation: Here, both the static and non-static fields are initialized with default value. The default value of int type is zero. Static constructor will initialize only static fields. Here static field is s. While the non-static field(ns) is initialized by the non-static constructor.
Parameters: We cannot pass any parameters to the static constructors because these are called implicitly and for passing parameters, we have to call it explicitly which is not possible. It will give runtime error as shown in below example. However, we can pass the parameters to the non-static constructors.
*access modifiers are not allowed on static constructors

* like below we cannot initialize a value for non-static member in static constructer 
int s;
static Geeks()
{
s = 5;
    Console.WriteLine("Static constructor");
}

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


Difference between readonly and const keyword in C#


In C#, a const keyword is used to declare constant fields and constant local. The value of the constant field is the same throughout the program or in other words, once the constant field is assigned the value of this field is not be changed. In C#, constant fields and locals are not variables, a constant is a number, string, null reference, boolean values.

// C# program to illustrate the 
// use of const keyword 
using System; 

class GFG { 

// Constant fields 
public const int myvar = 10; 
public const string str = "GeeksforGeeks"; 

// Main method 
static public void Main() 

// Display the value of Constant fields 
Console.WriteLine("The value of myvar: {0}", myvar); 
Console.WriteLine("The value of str: {0}", str); 

In C#, you can use a readonly keyword to declare a readonly variable. This readonly keyword shows that you can assign the variable only when you declare a variable or in a constructor of the same class in which it is declared.

// C# program to illustrate the use 
// of the readonly keyword 
using System; 

class GFG { 

// readonly variables 
public readonly int myvar1; 
public readonly int myvar2; 

// Values of the readonly 
// variables are assigned 
// Using constructor 
public GFG(int b, int c) 

myvar1 = b; 
myvar2 = c; 
Console.WriteLine("Display value of myvar1 {0}, "+ 
"and myvar2 {1}", myvar1, myvar2); 

// Main method 
static public void Main() 
GFG obj1 = new GFG(100, 200); 






What is the difference between ExecuteScalar, ExecuteReader and ExecuteNonQuery

ExecuteScalar() only returns the value from the first column of the first row of your query.
ExecuteReader() returns an object that can iterate over the entire result set.
- It is very useful to use with aggregate functions like Count(*) or Sum() etc. When compare to ExecuteReader() , ExecuteScalar() uses fewer System resources.

ExecuteNonQuery() does not return data at all: only the number of rows affected by an insert, update, or delete

It is very useful to use with aggregate functions like Count(*) or Sum() etc. When compare to ExecuteReader() , ExecuteScalar() uses fewer System resources.



Dependency Injection

https://m.youtube.com/watch?v=BPGtVpu81ek

https://www.codeproject.com/Articles/5248235/Dependency-Injection-DI-in-ASP-NET-Core


Tight Coupling

If a class directly or concretely has the dependency on another class, then it said to be tightly coupled. That means changing one object required to change another object as well. It's okay in a small application but in an enterprise-level application, it is too difficult to make the changes.

Loose Coupling


It ensures two objects are independent and the creation of objects outside the class without being dependent on other classes.

As I mentioned in the introduction section, Human class, and MobilePhone class dependency relationship and here is a code example without using DI. Human class is completely dependent on the MobilePhone class. It's a dependency. We can resolve this dependency by using Dependency Injection. Later, I will show the use of DI in the codebase by creating the ASP.NET Core MVC web project.

public class MobilePhone
{
public void CallFunction()
{
Console.WriteLine("It Ensure Mobile Call Function");
}

public void IneternetBrowse()
{
Console.WriteLine("It Ensure Internet Browse Function");
}
}

public class Human
{
MobilePhone _MobilePhone = new MobilePhone();
public void BasciNeed()
{
_MobilePhone.CallFunction();
_MobilePhone.IneternetBrowse();
}
}
The problem is when in the future the MobilePhone class has changed, then you have to change Human as well. For example, if MobilePhone class adds a new parameter base constructor, then the Human class absorbs it by changing the current implementation. To solve this complexity, we have to use DI.

DI container helps us by creating an object outside the class and providing it at the right time when we required it so that we don't think about object creation. As a result, our code becomes clean, maintainable and loosely coupled.

Classification of DI

  • Constructor Injection
  • Setter Injection
  • Method Injection
Now I will illustrate Constructor Injection with details examples.

Let's see the above example using Constructor Injection. DI is served as a service. When we need MobilePhone class object, we just knock the DI container, please give us the expected object. We don't have any worry regarding object creation and changed the existing code as well. DI container will make sure of it. It's a great relief.


public interface IMobilePhone
{
void CallFunction();
void IneternetBrowse();
}

public class MobilePhone : IMobilePhone
{
public void CallFunction()
{
Console.WriteLine("It Ensure Mobile Call Function");
}

public void IneternetBrowse()
{
Console.WriteLine("It Ensure Internet Browse Function");
}
}

public class Human
{
IMobilePhone _mobilePhone;
public Human(IMobilePhone mobilePhone)
{
_mobilePhone = mobilePhone;
}
public void BasciNeed()
{
_mobilePhone.CallFunction();
_mobilePhone.IneternetBrowse();
}
}


async and await



public class Derived
{
  static void Main(string[] args)
{
Method();
        string s = "Test";
Console.WriteLine(s);
Console.ReadLine();
}

public static async void Method()
{
 await Task.Run(new Action(LongTask));
 Console.WriteLine("New Thread");
}

public static void LongTask()
{

Thread.Sleep(20000);

}
}

IEnumerable Interface


IEnumerable in C# is an interface that defines one method, GetEnumerator which returns an IEnumerator interface. This allows readonly access to a collection then a collection that implements IEnumerable can be used with a for-each statement.
 

Key Points

  1. IEnumerable interface contains the System.Collections.Generic namespace.
  2. IEnumerable interface is a generic interface which allows looping over generic or non-generic lists.
  3. IEnumerable interface also works with linq query expression.
  4. IEnumerable interface Returns an enumerator that iterates through the collection.


using System;
using System.Collections;
class name
{
    public string emp_name { get; set; }
    public name(string mystring)
    {
        emp_name = mystring;
    }
}



public class Employee : IEnumerable
{
     name[]  emp_names = new name[4];
     public Employee()
        {
        emp_names[0] = new name("Ajay");
        emp_names[1] = new name("Ajay 1");
        emp_names[2] = new name("Ajay 2");
        emp_names[3] = new name("Ajay 3");
        }
    public IEnumerator GetEnumerator()
    {
        return emp_names.GetEnumerator();
    }
}




class Program
{
    static void Main(string[] args)
    {
        Employee emp = new Employee();
        foreach(name n in emp)
        {
            Console.WriteLine(n.emp_name);
        }
        Console.ReadLine();
    }    
}




Params Array 



  • To Pass Multiple Parameter when we don't know the no of  parameters
  • It should be placed in last of method parameter
  • It should have only one type on the method , we cannot use int , string at the same time in params



Example

 public class Derived 

{
    static void Main(string[] args)
    {
        calc(10, 20, 30);

        int[] n = new int[3];

        n[0] = 1;
        n[1] = 2;
        n[2] = 3;

        calc(n);


        Console.ReadLine();

    }
    public static void calc(params int[] num)
    {
        foreach(int i in num)
        {
            Console.WriteLine(i);
        }
    }
}

Out keyword

  • To Return a value in parameter
  • Mostly used to call the multiple parameter method and return value from it.

public class Derived 
{
    static void Main(string[] args)
    {
        int sum = 0;
        int mul = 0;        
        calc(10, 10,out sum,out mul);
        Console.WriteLine("Sum {0}, Mul {0}", sum, mul);
        Console.ReadLine();        
    }
    public static void calc(int a, int b,out int sum,out int mul)
    {
        sum = a + b;
        mul = a * b;
    }
}



FEATUREARRAYARRAYLIST
MemoryThis has fixed size and can’t increase or decrease dynamically.Size can be increase or decrease dynamically.
Data TypeIn Arrays, we can store only one datatype either int, string, char etc.In Array List we can store different datatype variables.



TypedArrays are strongly typed which means it can store only specific type of items or elements.Array list are not strongly typed.
nullArray cannot accept null.Array List can accepts null.



Const

Let us  outline the differences between const and readonly variables.


  1. const fields need to be initialized with declaration only, while readonly fields can be initialized at declaration or in the constructor.
  2. const variables can be declared in methods, while readonly fields cannot be declared in methods.
  3. const fields cannot be used with static modifier, while readonly fields can be used with static modifier.
  4. const field is a compile-time constant, the readonly field can be used for run time constants.
A variable declared as const (read: constant) must be assigned a value at declaration, and this value may not then change at a later time.
Only primitive or "built-in" C# types (e.g. int, string, double) are allowed to be declared const.  Therefore, you cannot write either of these:

Static

static member (variable, method, etc) belongs to the type of an object rather than to an instance of that type.  Hence, if we declare this:


  • Static mostly used to call the methods without creating object .
public class MyClass
{
public static string MyMethod() { ... }
}
We must call this method like this:
var result = MyClass.MyMethod();
We will NOT be able to make calls like this:
var myClass = new MyClass();
var result = myClass.MyMethod(); //Will not compile
Now there's only one keyword left to define: readonly.

Readonly

readonly field is one where assignment to that field can only occur as part of the declaration of the class or in a constructor.
public class TestClass
{
public readonly string ConnectionString = "TestConnection";
public TestClass()
{
ConnectionString = "DifferentConnection";
}
public void TestMethod ()
{
ConnectionString = "NewConnection";//Will not compile
}
}
This means that a readonly variable can have different values for different constructors in the same class.



Abstraction








public abstract class Customer{

    public abstract void Print();

}

public class Derived : Customer{

    static void Main(string[] args){   

        //Parent Class Reference Variable can point derived class object
        Customer D = new Derived();
       //Or Derived D = new Derived();

        D.Print();

        Console.ReadLine();

    }

    public override void Print(){

        Console.WriteLine("Print Called");

    }

}



Method Hiding


  •  Reimplement the method of the base class 
  •  Using new keyword 
  •  It hides the method of the base class 

using System;
  
// Base Class
public class My_Family {
  
    public void member()
    {
        Console.WriteLine("Total number of family members: 3");
    }
}
  
// Derived Class
public class My_Member : My_Family {
  
    // Reimplement the method of the base class
    // Using new keyword
    // It hides the method of the base class
    public new void member() 
    {
        Console.WriteLine("Name: Rakesh, Age: 40 \nName: Somya, "+
                               "Age: 39 \nName: Rohan, Age: 20 ");
    }
}
  
// Driver Class
class GFG {
  
    // Main method
    static public void Main()
    {
  
        // Creating the object of the derived class
        My_Member obj = new My_Member();
  
        // Access the method of derived class
        obj.member();
    }
}
Output:

Name: Rakesh, Age: 40
Name: Somya, Age: 39
Name: Rohan, Age: 20


REF Parameter


- C# provides a ref keyword to pass parameters as reference type
- It Passes the address of parameter to function rather than the original value


class Program
    {
        public void Show(ref int val)
        {
            val *= val; // Manipulating value  
            Console.WriteLine("Value inside the show function " + val);
            // No return statement  
        }
        // Main function, execution entry point of the program  
        static void Main(string[] args)
        {
            int val = 50;
            Program program = new Program(); // Creating Object  
            Console.WriteLine("Value before calling the function " + val);
            program.Show(ref val); // Calling Function by passing reference            
            Console.WriteLine("Value after calling the function " + val);
        }
    }



Factorial
So we will calculate the factorial like this.


4!=4x(4-1)x(4-2)x(4-3)=24


class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Please Enter a Number");


            //read number from user    
            int number = Convert.ToInt32(Console.ReadLine());


            //invoke the static method    
            double factorial = Factorial(number);


            //print the factorial result    
            Console.WriteLine("factorial of" + number + "=" + factorial.ToString());


        }
        public static double Factorial(int number)
        {
            if (number == 0)
                return 1;
            return number * Factorial(number - 1);//Recursive call    


        }
    }
___________________________________________________


struct  array


We have learned class in the previous section. Class is a reference type. C# includes a value type entity same as class called "structure". Structs are mainly useful to hold small data values. A structure can be defined using the struct operator. It can contain parameterized constructor, static constructor, constants, fields, methods, properties, indexers, operators, events and nested types.


struct  array


public class MainClass
    {
        private struct book
        {
            public int id;
            public string name;
        }
        private static void Main()
        {
            book[] b = new book[]
            {
                new book{id=1,name="BG"},
                new book{id=2,name="GBG"},
                new book{id=3,name="AsBG"}
            };
            //book b;
            //b.id = 1;
            //b.name = "BG";


            //b.id = 2;
            //b.name = "GP";
            foreach (var i in b)
            {
                Console.WriteLine(i.id + "." + i.name);
            }
            
            Console.ReadLine();
        }


    }

Interface













Multiple interface



_________________________________________________



public interface interfaceA



{


    void DrawA();
}
public interface interfaceB
{
    void DrawB();
}
class Program
{
    static void Main(string[] args)
    {


        TestC c = new TestC();
        c.DrawA();
        c.DrawB();
        Console.ReadLine();


    }
}


class TestA : interfaceA
{
    public void DrawA()
    {
        Console.WriteLine("This is Class One");
    }
}


class TestB : interfaceB
{
    public void DrawB()
    {
        Console.WriteLine("This is Class Two");
    }
}


class TestC : interfaceA, interfaceB
{
    TestA a = new TestA();
    TestB b = new TestB();    
    public void DrawA()
    {
        a.DrawA();
    }
    public void DrawB()
    {
        b.DrawB(); 
    }   
}



Delegate
_________________________________________________



Now I want to write a method in the Employee class which can be used to promote the employees. The method that we are going to write will take a list of Employee objects as a parameter and then should print the names of all the employees who are eligible for a promotion.
But the logic based on which the employee gets promoted should not be hardcoded. At times we may promote employees based on their experience and at times we may promote them based on their salary or maybe some other condition. So, the logic to promote employees should not be hard-coded within the method.


using System;
public delegate int Calculator(int n);//declaring delegate  


public class DelegateExample
{
    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;
    }
    public static void Main(string[] args)
    {
        Calculator c1 = new Calculator(add);//instantiating delegate  
        Calculator c2 = new Calculator(mul);
        c1(20);//calling method using delegate  
        Console.WriteLine("After c1 delegate, Number is: " + getNumber());
        c2(3);
        Console.WriteLine("After c2 delegate, Number is: " + getNumber());
        Console.ReadLine();
    }


}



MultiCast Delegate
_________________________________________________
using System;


delegate int NumberChanger(int n);
namespace DelegateAppl
{
    class TestDelegate
    {
        static int num = 10;


        public static int AddNum(int p)
        {
            num += p;
            return num;
        }
        public static int MultNum(int q)
        {
            num *= q;
            return num;
        }
        public static int getNum()
        {
            return num;
        }
        static void Main(string[] args)
        {
            //create delegate instances
            NumberChanger nc;


            NumberChanger nc1 = new NumberChanger(AddNum);
            NumberChanger nc2 = new NumberChanger(MultNum);


            nc = nc1;
            nc += nc2;


            //calling multicast
            nc(5);
            Console.WriteLine("Value of Num: {0}", getNum());
            Console.ReadKey();
        }
    }


}


Custom Exception


using System;
using System.Text.RegularExpressions;
namespace DelegateAppl
{
    class TestDelegate
    {
        static void Main(string[] args)
        {
            Student newStudent = null;


            try
            {
                newStudent = new Student();
                newStudent.StudentName = "James524";


                ValidateStudent(newStudent);
            }
            catch (customNameException ex)
            {
                Console.WriteLine(ex.Message);
            }


            Console.ReadKey();
        }
        private static void ValidateStudent(Student std)
        {
            Regex regex = new Regex("^[a-zA-Z]+$");


            if (!regex.IsMatch(std.StudentName))
                throw new customNameException(std.StudentName);


        }
    }


    class Student
    {
        public int StudentID { get; set; }
        public string StudentName { get; set; }
    }


    [Serializable]
    class customNameException : Exception
    {


        public customNameException(string name) : base(String.Format("Invalid Name: {0}", name))
        { }
    }


}


StringBuilder

- It used to store collection of character like strings
- But the difference is string keyword is immutable and it was mutable
- Whenever we make changes in string it will create new instance and memory
- But StringBuilder will Modify with Same Memory


Following is the pictorial representation of memory allocation for string in c# programming language.

C# String Memory Representation Diagram

Following is the pictorial representation of memory allocation for StringBuilder object in c# programming language.

C# StringBuilder Memory Representation Diagram


StringBuilder sb = new StringBuilder("Welcome to Tutlane",25);



Following table lists the important methods of StringBuilder which we can use to modify the contents of StringBuilder.

Method
Description
StringBuilder.Append
This method will append the given string value to the end of current StringBuilder.
StringBuilder.AppendFormat
It will replaces a format specifier passed in a string with formatted text.
StringBuilder.Insert
It inserts a string at the specified index of current StringBuilder.
StringBuilder.Remove
It removes a specified number of characters from the current StringBuilder.
StringBuilder.Replace
It replaces a specified character at a specified index.



Partial Class


- Partial Class Used to Split Class, Interface,Methods,Structures into Multiple Classes
- We Should Declare it with Partial Keyword
- All Partial Members should have same access modifier


namespace Pragim
{


   public class MainClass
   {


       {
       static void Main()


           PartialClass pc = new PartialClass();
           pc.HelloWorld();
            pc.HelloUniverse();


   public partial class PartialClass
           Console.ReadLine();
        }
    }
    {
        public void HelloWorld()


   public partial class PartialClass
       {
            Console.WriteLine("Hi Partial One");
        }
    }
    {


           Console.WriteLine("Hello Partial Two");
       public void HelloUniverse()
        {
        }
    }


}



C# Collections

In C#, collection represents group of objects. By the help of collections, we can perform various operations on objects such as
  • store object
  • update object
  • delete object
  • retrieve object
  • search object, and
  • sort object


Diffrences


List<T> 
store and fetch elements
- It can have duplicate elements


HashSet<T>
- Store , Remove ,View
- No Duplicates



SortedSet<T>
- Store , Remove ,View
- No Duplicates
- Stores in Asc order


Stack<T>
- Push , Pop
- Can Have Duplicates
- Stores in LIFO(Last in First Out)


Queue<T>
- Enqueue , Dequeue 
- Can Have Duplicates
- FIFO (First In First Out)


LinkedList<T>
- the concept of linked list. 
- It allows us to insert and delete elements fastly. 
- It can have duplicate elements.


Dictionary<key,value>
- It uses Key , Value type to store data
- Contains only unic keys
- By  using key we can easily store, find and remove values


 Dictionary<string, string> names = new Dictionary<string, string>();  


 names.Add("1","Sonoo"); 


SortedDictionary<key,value>
- Same as dic. but stores value in asc order
- It uses Key , Value type to store data
- Contains only unic keys
- By  using key we can easily store, find and remove values





REF Parameter


- C# provides a ref keyword to pass parameters as reference type
- It Passes the address of parameter to function rather than the original value


class Program
    {
        public void Show(ref int val)
        {
            val *= val; // Manipulating value  
            Console.WriteLine("Value inside the show function " + val);
            // No return statement  
        }
        // Main function, execution entry point of the program  
        static void Main(string[] args)
        {
            int val = 50;
            Program program = new Program(); // Creating Object  
            Console.WriteLine("Value before calling the function " + val);
            program.Show(ref val); // Calling Function by passing reference            
            Console.WriteLine("Value after calling the function " + val);
        }
    }



Factorial
So we will calculate the factorial like this.


4!=4x(4-1)x(4-2)x(4-3)=24


class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Please Enter a Number");


            //read number from user    
            int number = Convert.ToInt32(Console.ReadLine());


            //invoke the static method    
            double factorial = Factorial(number);


            //print the factorial result    
            Console.WriteLine("factorial of" + number + "=" + factorial.ToString());


        }
        public static double Factorial(int number)
        {
            if (number == 0)
                return 1;
            return number * Factorial(number - 1);//Recursive call    


        }
    }
___________________________________________________


struct  array


We have learned class in the previous section. Class is a reference type. C# includes a value type entity same as class called "structure". Structs are mainly useful to hold small data values. A structure can be defined using the struct operator. It can contain parameterized constructor, static constructor, constants, fields, methods, properties, indexers, operators, events and nested types.


struct  array


public class MainClass
    {
        private struct book
        {
            public int id;
            public string name;
        }
        private static void Main()
        {
            book[] b = new book[]
            {
                new book{id=1,name="BG"},
                new book{id=2,name="GBG"},
                new book{id=3,name="AsBG"}
            };
            //book b;
            //b.id = 1;
            //b.name = "BG";


            //b.id = 2;
            //b.name = "GP";
            foreach (var i in b)
            {
                Console.WriteLine(i.id + "." + i.name);
            }
            
            Console.ReadLine();
        }


    }





Multiple interface



_________________________________________________



public interface interfaceA



{


    void DrawA();
}
public interface interfaceB
{
    void DrawB();
}
class Program
{
    static void Main(string[] args)
    {


        TestC c = new TestC();
        c.DrawA();
        c.DrawB();
        Console.ReadLine();


    }
}


class TestA : interfaceA
{
    public void DrawA()
    {
        Console.WriteLine("This is Class One");
    }
}


class TestB : interfaceB
{
    public void DrawB()
    {
        Console.WriteLine("This is Class Two");
    }
}


class TestC : interfaceA, interfaceB
{
    TestA a = new TestA();
    TestB b = new TestB();    
    public void DrawA()
    {
        a.DrawA();
    }
    public void DrawB()
    {
        b.DrawB(); 
    }   
}



Delegate
_________________________________________________


Now I want to write a method in the Employee class which can be used to promote the employees. The method that we are going to write will take a list of Employee objects as a parameter and then should print the names of all the employees who are eligible for a promotion.
But the logic based on which the employee gets promoted should not be hardcoded. At times we may promote employees based on their experience and at times we may promote them based on their salary or maybe some other condition. So, the logic to promote employees should not be hard-coded within the method.


using System;
public delegate int Calculator(int n);//declaring delegate  


public class DelegateExample
{
    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;
    }
    public static void Main(string[] args)
    {
        Calculator c1 = new Calculator(add);//instantiating delegate  
        Calculator c2 = new Calculator(mul);
        c1(20);//calling method using delegate  
        Console.WriteLine("After c1 delegate, Number is: " + getNumber());
        c2(3);
        Console.WriteLine("After c2 delegate, Number is: " + getNumber());
        Console.ReadLine();
    }


}



MultiCast Delegate
_________________________________________________
using System;


delegate int NumberChanger(int n);
namespace DelegateAppl
{
    class TestDelegate
    {
        static int num = 10;


        public static int AddNum(int p)
        {
            num += p;
            return num;
        }
        public static int MultNum(int q)
        {
            num *= q;
            return num;
        }
        public static int getNum()
        {
            return num;
        }
        static void Main(string[] args)
        {
            //create delegate instances
            NumberChanger nc;


            NumberChanger nc1 = new NumberChanger(AddNum);
            NumberChanger nc2 = new NumberChanger(MultNum);


            nc = nc1;
            nc += nc2;


            //calling multicast
            nc(5);
            Console.WriteLine("Value of Num: {0}", getNum());
            Console.ReadKey();
        }
    }


}


Custom Exception


using System;
using System.Text.RegularExpressions;
namespace DelegateAppl
{
    class TestDelegate
    {
        static void Main(string[] args)
        {
            Student newStudent = null;


            try
            {
                newStudent = new Student();
                newStudent.StudentName = "James524";


                ValidateStudent(newStudent);
            }
            catch (customNameException ex)
            {
                Console.WriteLine(ex.Message);
            }


            Console.ReadKey();
        }
        private static void ValidateStudent(Student std)
        {
            Regex regex = new Regex("^[a-zA-Z]+$");


            if (!regex.IsMatch(std.StudentName))
                throw new customNameException(std.StudentName);


        }
    }


    class Student
    {
        public int StudentID { get; set; }
        public string StudentName { get; set; }
    }


    [Serializable]
    class customNameException : Exception
    {


        public customNameException(string name) : base(String.Format("Invalid Name: {0}", name))
        { }
    }


}


StringBuilder

- It used to store collection of character like strings
- But the difference is string keyword is immutable and it was mutable
- Whenever we make changes in string it will create new instance and memory
- But StringBuilder will Modify with Same Memory


Following is the pictorial representation of memory allocation for string in c# programming language.

C# String Memory Representation Diagram

Following is the pictorial representation of memory allocation for StringBuilder object in c# programming language.

C# StringBuilder Memory Representation Diagram


StringBuilder sb = new StringBuilder("Welcome to Tutlane",25);



Following table lists the important methods of StringBuilder which we can use to modify the contents of StringBuilder.

Method
Description
StringBuilder.Append
This method will append the given string value to the end of current StringBuilder.
StringBuilder.AppendFormat
It will replaces a format specifier passed in a string with formatted text.
StringBuilder.Insert
It inserts a string at the specified index of current StringBuilder.
StringBuilder.Remove
It removes a specified number of characters from the current StringBuilder.
StringBuilder.Replace
It replaces a specified character at a specified index.



Partial Class


- Partial Class Used to Split Class, Interface,Methods,Structures into Multiple Classes
- We Should Declare it with Partial Keyword
- All Partial Members should have same access modifier


namespace Pragim
{


   public class MainClass
   {


       {
       static void Main()


           PartialClass pc = new PartialClass();
           pc.HelloWorld();
            pc.HelloUniverse();


   public partial class PartialClass
           Console.ReadLine();
        }
    }
    {
        public void HelloWorld()


   public partial class PartialClass
       {
            Console.WriteLine("Hi Partial One");
        }
    }
    {


           Console.WriteLine("Hello Partial Two");
       public void HelloUniverse()
        {
        }
    }


}



C# Collections

In C#, collection represents group of objects. By the help of collections, we can perform various operations on objects such as
  • store object
  • update object
  • delete object
  • retrieve object
  • search object, and
  • sort object


Diffrences


List<T> 
store and fetch elements
- It can have duplicate elements


HashSet<T>
- Store , Remove ,View
- No Duplicates



SortedSet<T>
- Store , Remove ,View
- No Duplicates
- Stores in Asc order


Stack<T>
- Push , Pop
- Can Have Duplicates
- Stores in LIFO(Last in First Out)


Queue<T>
- Enqueue , Dequeue 
- Can Have Duplicates
- FIFO (First In First Out)


LinkedList<T>
- the concept of linked list. 
- It allows us to insert and delete elements fastly. 
- It can have duplicate elements.


Dictionary<key,value>
- It uses Key , Value type to store data
- Contains only unic keys
- By  using key we can easily store, find and remove values
 Dictionary<string, string> names = new Dictionary<string, string>();  
 names.Add("1","Sonoo"); 


SortedDictionary<key,value>
- Same as dic. but stores value in asc order
- It uses Key , Value type to store data
- Contains only unic keys
- By  using key we can easily store, find and remove values



















C# | Random.Next() Method


using System;

using System.Text;
class RandomNumberSample
{
    static void Main(string[] args)
    {
        RandomGenerator generator = new RandomGenerator();
        int rand = generator.RandomNumber(5, 100);
        Console.WriteLine($"Random number between 5 and 100 is {rand}");
        string str = generator.RandomString(10, false);
        Console.WriteLine($"Random string of 10 chars is {str}");
        string pass = generator.RandomPassword();
        Console.WriteLine($"Random string of 6 chars is {pass}");
        Console.ReadLine();
    }
}
public class RandomGenerator
{
    // Generate a random number between two numbers 
    public int RandomNumber(int min, int max)
    {
        Random random = new Random();
        return random.Next(min, max);
    }
    // Generate a random string with a given size 
    public string RandomString(int size, bool lowerCase)
    {
        StringBuilder builder = new StringBuilder();
        Random random = new Random();
        char ch;
        for (int i = 0; i < size; i++)
        {
            ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
            builder.Append(ch);
        }
        if (lowerCase)
        return builder.ToString().ToLower();
        return builder.ToString();
    }
    // Generate a random password 
    public string RandomPassword()
    {
        StringBuilder builder = new StringBuilder();
        builder.Append(RandomString(4, true));
        builder.Append(RandomNumber(1000, 9999));
        builder.Append(RandomString(2, false));
        return builder.ToString();
    }
}

Comments

Popular Posts