Delgates , Events And Lambda expressions

Delegates

delegate is defined using the delegate keyword. The declaration looks like a function signature, but the compiler actually introduces a class that can hold references to methods whose signatures match the signature of the delegate. A delegate can hold references to either static or instance methods.

public enum Status { Started, Stopped }
public delegate void StatusChange(Status status);
public class Engine
{
    private StatusChange statusChangeHandler;// is Delegate return true
    public void RegisterStatusChangeHandler(StatusChange handler)
    {
        statusChangeHandler = handler;
    }
    public void Start()
    {
        // start the engine
        if (statusChangeHandler != null)
            statusChangeHandler(Status.Started);
    }
    public void Stop()
    {
        // stop the engine
        if (statusChangeHandler != null)
            statusChangeHandler(Status.Stopped);
    }
}

Combining delegates

ExpressionResult
null + d1d1
d1 + nulld1
d1 + d2[d1, d2]
d1 + [d2, d3][d1, d2, d3]
[d1, d2] + [d2, d3][d1, d2, d2, d3]
[d1, d2] – d1d2
[d1, d2] – d2d1
[d1, d2, d1] – d1[d1, d2]
[d1, d2, d3] – [d1, d2]d3
[d1, d2, d3] – [d2, d1][d1, d2, d3]
[d1, d2, d3, d1, d2] – [d1, d2][d1, d2, d3]
[d1, d2] – [d1, d2]null

Events

Events aren’t Delegate instances.

using System;

class Test
{
    public event EventHandler MyEvent
    {
        add
        {
            Console.WriteLine ("add operation");
        }
        
        remove
        {
            Console.WriteLine ("remove operation");
        }
    }  
    static void Main()
    {
        Test t = new Test();
        
        t.MyEvent += new EventHandler (t.DoNothing);
        t.MyEvent -= null;
    }
    void DoNothing (object sender, EventArgs e)
    {
    }
}
private EventHandler _myEvent;
    
public event EventHandler MyEvent
{
    add
    {
        lock (this)
        {
            _myEvent += value;
        }
    }
    remove
    {
        lock (this)
        {
            _myEvent -= value;
        }
    }        
}

Lambda expressions

  • The variables that are introduced in a lambda expression are not visible outside the lambda (for instance, in the enclosing method).
  • A lambda cannot capture inref, or out parameters from the enclosing method.
  • Variables that are captured by a lambda expression are not garbage collected, even if they would otherwise go out of scope until the delegate that the lambda is assigned to is garbage collected.
bool IsOdd(int n) { return n % 2 == 1; }
var list = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
list.RemoveAll(IsOdd);
var list = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
list.RemoveAll(delegate (int n) { return n % 2 == 1; });
var list = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
list.RemoveAll(n => n % 2 == 1);

Collections

IEnumerable and IEnumerator

IEnumerable is an interface defining a single method GetEnumerator() that returns an IEnumerator interface.
This works for readonly access to a collection that implements that IEnumerable can be used with a foreach statement.
IEnumerator has two methods MoveNext and Reset. It also has a property called Current

class Demo : IEnumerable, IEnumerator {
   // IEnumerable method GetEnumerator()
   IEnumerator IEnumerable.GetEnumerator() {
      throw new NotImplementedException();
   }
   public object Current {
      get { throw new NotImplementedException(); }
   }
   // IEnumertor method
   public bool MoveNext() {
      throw new NotImplementedException();
   }
   // IEnumertor method
      public void Reset() {
      throw new NotImplementedException();
   }
}

List<T> collection

List<T> uses an array to store the elements. When the number of elements exceeds the size of the array, a new and larger array is allocated, and the content of the previous array is copied to the new one. 

var numbers = new List<int> {1, 2, 3}; // 1 2 3
numbers.Add(5);                        // 1 2 3 5
numbers.AddRange(new int[] { 7, 11 }); // 1 2 3 5 7 11
numbers.Insert(5, 1);                  // 1 2 3 5 7 1 11
numbers.Insert(5, 1);                  // 1 2 3 5 7 1 1 11
numbers.InsertRange(                   // 1 13 17 19 2 3 5..
    1, new int[] {13, 17, 19});        // ..7 1 1 11

numbers.Remove(1);              // 13 17 19  2  3  5  7  1  
                                // 1 11
numbers.RemoveRange(2, 3);      // 13 17  5  7  1  1 11
numbers.RemoveAll(e => e < 10); // 13 17 11
numbers.RemoveAt(1);            // 13 11
numbers.Clear();                // empty

var numbers = new List<int> { 1, 2, 3, 5, 7, 11 };
var a = numbers.Find(e => e < 10);      // 1
var b = numbers.FindLast(e => e < 10);  // 7
var c = numbers.FindAll(e => e < 10);   // 1 2 3 5 7

var numbers = new List<int> { 1, 1, 2, 3, 5, 8, 11 };
var a = numbers.FindIndex(e => e < 10);     // 0
var b = numbers.FindLastIndex(e => e < 10); // 5
var c = numbers.IndexOf(5);                 // 4
var d = numbers.LastIndexOf(1);             // 1
var e = numbers.BinarySearch(8);            // 5

var numbers = new List<int> { 1, 5, 3, 11, 8, 1, 2 };
numbers.Sort();     // 1 1 2 3 5 8 11
numbers.Reverse();  // 11 8 5 3 2 1 1

Sort() sorts the list according to a default or specified criteria. There are several overloads that allow us to specify either a comparison delegate or an IComparer<T> object, or even a sub-range of the list to sort. This operation is performed in O(n log n) in most cases but O (n2) in the worst-case scenario.

The Dictionary<TKey, TValue> collection

var languages = new Dictionary<int, string>()
{
    {1, "C#"}, 
    {2, "Java"}, 
    {3, "Python"}, 
    {4, "C++"}
};
languages.Add(5, "JavaScript");
languages.TryAdd(5, "JavaScript");
languages[6] = "F#";
languages[5] = "TypeScript";
Console.WriteLine($"Has 5: {languages.ContainsKey(5)}");
Console.WriteLine($"Has C#: {languages.ContainsValue("C#")}");

We can also iterate through the elements of a dictionary using an enumerator, in which case the key-value pairs are retrieved as KeyValuePair<TKey, TValue> objects:

foreach(var kvp in languages)
{
    Console.WriteLine($"[{kvp.Key}] = {kvp.Value}");
}

LINQ

class A : IComparable
{
    public int value{get;private set;}
    public A(int v)=>this.value = v;
    public int CompareTo(object obj) => this.value - (obj as A).value;
}


List<A> values2 = new List<A> { new A(v:34), new A(v: 45), new A(v: 76), new A(v: 23), new A(v: 54), new A(v: 33), new A(v: 65),new A(v:33), new A(v:23) };
var res = from x in values2 where x.value>50 orderby x ascending select x;
foreach(A v in res){ Console.WriteLine(v.value);}

var res = from x in values2 group x by x.value into gg where gg.Key>30  orderby gg.Key ascending select gg.Key ;
foreach(var v in res){ Console.WriteLine(v);}//33,34,45.....
int[] arr=new int[]{1,23,21,4,34,21,44,2,31,53,21,123};
var res323=arr.TakeLast(3).OrderBy(x=>x).Distinct().Zip( arr.TakeLast(3), (x,y)=>(x,y));

foreach (var (x,y) in res323)
{
    Console.WriteLine(x+" "+y);
}

Generic

Generic types

class Pair<T, U>
{
    public T Item1 { get; private set; }
    public U Item2 { get; private set; }
    public Pair(T item1, U item2)
    {
        Item1 = item1;
        Item2 = item2;
    }
}
var p1 = new Pair<int, int>(1, 2);
var p2 = new Pair<int, double>(1, 42.99);
var p3 = new Pair<string, bool>("true", true);
public abstract class Shape<T>
{
    public abstract T Area { get; }
}

public class Square : Shape<int>
{
    public int Length { get; set; }
    public Square(int length)
    {
        Length = length;
    }
    public override int Area => Length * Length;
}

public class Square<T> : Shape<T>
{
    public T Length { get; set; }
    public Square(T length)
    {
        Length = length;
    }
    /* ERROR: Operator '*' cannot be applied to operands 
    of type 'T' and 'T' */
    public override T Area => Length * Length;
}

Variant generic interfaces

  • covariant type parameter is declared with the out keyword and allows an interface method to have a return type that is more derived than the specified type parameter.
  • contravariant type parameter is declared with the in keyword and allows an interface method to have a parameter that is less derived than the specified type parameter.
public interface IEnumerable
{
    IEnumerator GetEnumerator();
}
public interface IEnumerable<out T> : IEnumerable
{
    IEnumerator<T> GetEnumerator();
}

IEnumerable<string> names = 
   new List<string> { "Marius", "Ankit", "Raffaele" };
IEnumerable<object> objects = names;
public interface F
{}
public class FF : F
{}
F<object> str = new FF<string>();

Generic methods

class CompareObjects
{
    public bool Compare<T>(T input1, T input2)
    {
        return input1.Equals(input2);
    }
}
struct Point<T>
    where T : struct, 
              IComparable, IComparable<T>,
              IConvertible,
              IEquatable<T>,
              IFormattable
{
    public T X { get; }
    public T Y { get; }
    public Point(T x, T y)
    {
        X = x;
        Y = y;
    }
}

Object-Oriented Programming

Virtual members

In the preceding example, we have seen a virtual method. This is a method that has an implementation in a base class but can be overridden in derived classes, which is helpful for changing implementation details. Methods are non-virtual by default. A virtual method in a base class is declared with the virtual keyword. An overridden implementation of a virtual method in a derived class is defined with the override keyword, instead of the virtual keyword. The method signature of the virtual and overridden methods must match.

Methods are not the only class members that can be virtual. The virtual keyword can be applied to properties, indexers, and events. However, the virtual modifier cannot be used together with staticabstractprivate, or override modifiers.

A virtual member that is overridden in a derived class can be further overridden in a class derived from the derived class. This chain of virtual inheritance continues indefinitely unless explicitly stopped with the use of the sealed keyword

class GameUnit
{
    public Position Position { get; protected set; }
    public GameUnit(Position position)
    {
        Position = position;
    }
    public void Draw(Surface surface)
    {
        surface.DrawAt(Image, Position);
    }
    protected virtual char Image => ' ';
}
class Terrain : GameUnit
{
    public Terrain(Position position) : base(position) { }
}
class Water : Terrain
{
    public Water(Position position) : base(position) { }
    protected override char Image => '░';
}
class Hill : Terrain
{
    public Hill(Position position) : base(position) { }
    protected override char Image => '≡';
}

abstract classes and members

An abstract class is declared using the abstract keyword. An abstract class cannot be instantiated, which means we cannot create the object of an abstract class. 

abstract class GameUnit
{
    public Position Position { get; protected set; }
    public GameUnit(Position position)
    {
        Position = position;
    }
    public void Draw(Surface surface)
    {
        surface.DrawAt(Image, Position);
    }
    protected abstract char Image { get; }
}
abstract class Terrain : GameUnit
{
    public Terrain(Position position) : base(position) { }
}
class Water : Terrain
{
    public Water(Position position) : base(position) { }
    protected override char Image => '░';
}
class Hill : Terrain
{
    public Hill(Position position) : base(position) { }
    protected override char Image => '≡';
}
  • An abstract class can have both abstract and non-abstract members.
  • If a class contains an abstract member, then the class must be marked abstract.
  • An abstract member cannot be private.
  • An abstract member cannot have an implementation.
  • An abstract class must provide an implementation for all of the members of all of the interfaces it implements (if any).
  • An abstract method is implicitly a virtual method.
  • Members declared abstract cannot be static or virtual.
  • The implementation in a derived class must specify the override keyword in the declaration of the member.

Sealed classes and members

sealed class Water : Terrain
{
   public Water(Position position) : base(position) { }
   protected override char Image => '░';
}
class Lake : Water  // ERROR: cannot derived from sealed type
{
   public Lake(Position position) : base(position) { }
}
class Water : Terrain
{
    public Water(Position position) : base(position) { }
    protected sealed override char Image => '░';
}
      
class Lake : Water
{
    public Lake(Position position) : base(position) { }
    protected sealed override char Image => '░';  // ERROR
}

Hiding base class members

class Base
{
    public int Get() { return 42; }
}
class Derived : Base
{
    public new int Get() { return 10; }
}
Derived d = new Derived();
Console.WriteLine(d.Get()); // prints 10
Base b = d;
Console.WriteLine(b.Get()); // prints 42

Interfaces

  • An interface can contain only methods, properties, indexers, and events. They cannot contain fields.
  • If a type implements an interface, then it must provide an implementation for all of the members of the interface. The method signature and return type of the method of an interface cannot be altered by the type that is implementing the interface.
  • When an interface defines properties or indexers, an implementation can provide extra accessors for them. For instance, if a property in an interface has only the get accessor, the implementation can also provide a set accessor.
  • An interface cannot have constructors or operators.
  • An interface cannot have static members.
  • The interface members are implicitly defined as public. If you try to use an access modifier with a member of an interface, it will result in a compile-time error.
  • An interface can be implemented by multiple types. A type can implement multiple interfaces.
  • If a class is inheriting from another class and simultaneously implementing an interface, then the base class name must come before the name of the interface separated by a comma.
  • Typically, an interface name starts with the letter I, such as IEnumerableIList<T>, and so on.
interface ISurface
{
    void BeginDraw();
    void EndDraw();
    void DrawAt(char c, Position position);
}

class Surface : ISurface
{
    private int left;
    private int top;
    public void BeginDraw()
    {
        Console.Clear();
        left = Console.CursorLeft;
        top = Console.CursorTop;
    }
    public void EndDraw()
    {
        Console.WriteLine();
    }
    public void DrawAt(char c, Position position)
    {
        try
        {
            Console.SetCursorPosition(left + position.X, 
                                      top + position.Y);
            Console.Write(c);
        }
        catch (ArgumentOutOfRangeException e)
        {
            Console.Clear();
            Console.WriteLine(e.Message);
        }
    }
}
interface A
{
    public void fun1();
    int data { set; get; }
}
public class B :A{ 
    void A.fun1(){}
    public int data {set; get;}
}


B b=new B();
b.data = 12;
//b.fun1() error
(b as A).fun1();

Structures , Enumerations and Namespaces

Structures

Value types are defined using the struct keyword instead of class. In most aspects, structures are identical to classes and the characteristics presented in this chapter for classes apply to structures too. However, there are several key differences:

  • Structures do not support inheritance. Although a structure can implement any number of interfaces, it cannot derive from another structure. For this reason, structure members cannot have the protected access modifier. Also, a structured method or property cannot be abstract or virtual.
  • A structure cannot declare a default (parameterless) constructor.
  • Structures can be instantiated without using the new operator.
  • In a structure declaration, fields cannot be initialized unless they are declared const or static.

Enumerations

enum Priority:byte
{
    Low = 10,
    Normal,//11
    Important = 20,
    Urgent//21
}
Priority p = Priority.Normal;
int i = (int)Priority.Normal;
Enum.TryParse("Normal", out Priority p); // p is Normal
Enum.TryParse(typeof(Priority), "normal", true, out object o);
Priority p = (Priority)o;   // p is Normal

Namespaces

namespace chapter_04
{
   namespace demo
   {
      class foo { }
   }
}

//or 

namespace chapter_04.demo
{
   class foo { }
}

There is an implicit namespace that is the root of all namespaces (and contains all namespaces and types that are not declared in a named namespace). This namespace is called global. If you need to include it to specify a fully qualified name, then you must separate it with :: and not with a dot, as in global::System.String. This can be necessary in situations where namespace names collide. Here is an example:

Classes and Objects

Classes

Fields

class Employee
{
   public const int StartId = 100;
   public readonly int EmployeeId;
   public string       FirstName;
   public string       LastName;
   public Employee(int id)
   {
      EmployeeId = id;
   }
}
Employee obj = new Employee(1);
obj.FirstName = "John";
obj.LastName = "Doe";

Methods

class Employee
{
    public int    EmployeeId;
    public string FirstName;
    public string LastName;
    public string GetEmployeeName()
    {
        return $"{FirstName} {LastName}";
    }
    public string GetEmployeeName() => $"{FirstName} {LastName}";
}
  • An access modifier: This specifies the visibility of the method. This is optional and private by default.
  • Modifiers such as virtualabstractsealed, or static
  • A return type: This could be void if the method does not return any value.
  • A name: This must be a valid identifier.
  • Zero, one, or more parameters: These are specified with a type, name, and optionally, the refin, or out specifier.
class Employee
{
    public int EmployeeId;
    public string FirstName;
    public string LastName;
    public Employee(int employeeId, 
                    string firstName, string lastName)
    {
        EmployeeId = employeeId;
        FirstName = firstName;
        LastName = lastName;
    }
    public string GetEmployeeName() => 
           $"{FirstName} {LastName}";   
}

Employee obj = new Employee(1, "John", "Doe");
//Considering the Employee class without a user-defined constructor
Employee obj = new Employee()
{
    EmployeeId = 1,
    FirstName = "John",
    LastName = "Doe"
};

Properties

class Employee
{
   private int employeeId;
   private string firstName;
   private string lastName;
   public int EmployeeId
   {
      get { return employeeId; }
      set { employeeId = value; }
   }
   public string FirstName
   {
      get { return firstName; }
      set { firstName = value; }
   }
   public string LastName
   {
      get { return lastName; }
      set { lastName = value; }
   }
   public string val
   {
      get{}
      private set {}
   }
}
class Employee
{
    public int EmployeeId { get; private set; }
    public string FirstName { get; private set; }
    public string LastName { get; private set; }
    public Employee(int id, string firstName, string lastName)
    {
        EmployeeId = id;
        FirstName = firstName;
        LastName = lastName;
    }
}
class Employee
{
   public int EmployeeId { get; set; } = 1;//initialized with 1
   public string FirstName { get; set; }
   public string LastName { get; set; }
}

Indexers

class ProjectRoles
{
    readonly Dictionary<int, string> roles = 
        new Dictionary<int, string>();
    public string this[int projectId]
    {
        get
        {
            if (!roles.TryGetValue(projectId, out string role))
                throw new Exception("Project ID not found!");
            return role;
        }
        set
        {
            roles[projectId] = value;
        }
    }
}

this keyword

class Employee
{
    public int EmployeeID;
    public string FirstName;
    public string LastName;
    public Employee(int EmployeeID, 
                    string FirstName, string LastName)
    {
       this.EmployeeID = EmployeeID;
       this.FirstName = FirstName;
       this.LastName = LastName;
    }
}

Static members

class Employee
{
    private static int id = 1;
    public int EmployeeId { get; private set; }
    public string FirstName { get; private set; }
    public string LastName { get; private set; }
    private Employee(int id, string firstName, string lastName)
    {
        EmployeeId = id;
        FirstName = firstName;
        LastName = lastName;
    }
    public static Employee Create(string firstName, 
                                  string lastName)
    {
        return new Employee(id++, firstName, lastName);
    }
}

Static classes

static class cannot be instantiated. Since we cannot create instances of a static class

static class MassConverters
{
    public static double PoundToKg(double pounds)
    {
        return pounds * 0.45359237;
    }
    public static double KgToPound(double kgs)
    {
        return kgs * 2.20462262185;
    }
}
var lbs = MassConverters.KgToPound(42.5);
var kgs = MassConverters.PoundToKg(180);

static constructor

  • In a static class when the first static member of the class is accessed for the first time
  • In a non-static class when the class is instantiated for the first time

ref, in, and out parameters

ref keyword allows us to create a call-by-reference mechanism rather than a call-by-value mechanism. A ref keyword is specified when we declare and invoke the method.

class Program
{
    static void Swap(ref int a, ref int b)
    {
        int temp = a;
        a = b;
        b = temp;
    }
    static void Main(string[] args)
    {
        int num1 = 10;
        int num2 = 20;
        Console.WriteLine($"Before swapping: num1={num1}, num2={num2}");
        Swap(ref num1, ref num2);
        Console.WriteLine($"After swapping:  num1={num1}, num2={num2}");
    }
}
class Project
{
    Employee owner;
    public string Name { get; private set; }
    public Project(string name, Employee owner)
    {
        Name = name;
        this.owner = owner;
    }
    public ref Employee GetOwner()
    {
        return ref owner;
    }
    public override string ToString() => 
      $"{Name} (Owner={owner.FirstName} {owner.LastName})";
}
  • It is not possible to return a reference to a local variable.
  • It is not possible to return a reference to this.
  • It is possible to return references to class fields but also to properties without a set accessor.
  • It is possible to return a reference to ref/in/out parameters.
  • Returning by reference breaks the encapsulation because the caller gets full access to the state, or parts of the state, of an object.

The in keyword is very similar to the ref keyword. It causes an argument to be passed by reference. However, the key difference is that an in argument cannot be modified by the called method. An in parameter is basically a readonly ref parameter.

static void DontTouch(in int value, in string text)
{
    value = 42;   // error
    ++value;      // error
    text = null;  // error
}
int i = 0;
string s = "hello";
DontTouch(i, s);

The out keyword is similar to the ref keyword. The difference is that a variable passed as an out argument does not have to be initialized before the method called, but the method taking an out parameter must assign a value to it before returning.

Methods with a variable number of arguments

static bool Any(params bool [] values)
{
    foreach (bool v in values)
        if (v) return true;
    return false;
}
static bool All(params bool[] values)
{
    if (values.Length == 0) return false;
    foreach (bool v in values)
        if (!v) return false;
    return true;
}

Named arguments

struct Point
{
    public int X { get; }
    public int Y { get; }
    public Point(int x = 0, int y = 0)
    {
        X = x;
        Y = y;
    }
}

Point p1 = new Point(x: 1, y: 2); // x = 1, y = 2
Point p2 = new Point(1, y: 2);    // x = 1, y = 2
Point p3 = new Point(x: 1, 2);    // x = 1, y = 2
Point p4 = new Point(y: 2);       // x = 0, y = 2
Point p5 = new Point(x: 1);       // x = 1, y = 0

Access modifiers

  • public: A public field can be accessed by any part of the code in the same assembly or in another assembly.
  • protected: A protected type or member can be accessed only in the current class and in a derived class.
  • internal: An internal type or member is accessible only within the current assembly.
  • protected internal: This is a combination of protected and internal access levels. A protected internal type or member is accessible in the current assembly or in a derived class.
  • private: A private type or member can be accessed only inside the class or struct. This is the least-accessible level defined in C#.
  • private protected: This is a combination of private and protected access levels. A private protected type or type member is accessible by code in the same class, or in a derived class, but only within the same assembly.

Partial classes

partial class Employee
{
    partial void Promote();
}
partial class Employee
{
    public int EmployeeId { get; set; }
}
partial class Employee
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    partial void Promote()
    {
        Console.WriteLine("Employee promoted!");
    }
}