Wednesday, May 20, 2015

6. Delegates

A delegate is a reference to a function (single cast delegate) or to multiple functions (multi cast delegate)

Here's the implementation of a multi cast delegate:

//1. Declaration
public delegate void MyDelagate(int a, int b); 
public class Example
{
 // methods to be assigned and called by delegate
 public void Sum(int a, int b)
 {
 Console.WriteLine("Sum of integers is = " + (a + b));
 }
 
 public void Difference(int a, int b)
 {
 Console.WriteLine("Difference of integer is = " + (a - b));
 }
}
class Program
{
 static void Main()
 {
 Example obj = new Example();
 // 2. Instantiation
 MyDelagate multicastdel = new MyDelagate(obj.Sum); 
 multicastdel += new MyDelagate(obj.Difference);
 
 // 3. Invocation
 multicastdel (50, 20);
 }
}
 
/* Out put
 
 Sum of integers is = 70 
 Difference of integer is = 30
 
*/

5. Law of Demeter


"Don't talk to strangers". It's the simple explanation of the Demeter's Law.


It's also known as the "Law of train wrecks"
A -> B -> C

A should only know about it's closest "friends". It shouldn't access something from C. Instead, it should tell B to DO something, not to ask B about C.

TELL, DON'T ASK

A method M of an object O may only call the methods/params of the following:

1. O itself

2. M's parameters
3. Any object CREATED within M
4. O's direct component objects (O's instance variables)

Example:

public void ShowBallance(BankAccount account)
{
    Money amount = account.GetBallance();
    this.PrintToScreen(amount.PrintFormat());
}


This violates the low, because it can be written like:
this.PrintToScreen(account.GetBallance().PrintFormat()); // it's an obvious violation

Code should be:

public void ShowBallance(BankAccount account)

{
  account.PrintBallance(); // TELL, DON'T ASK!
}
 
 
 

Thursday, May 14, 2015

4. Extension Methods

Extension Method = static method of a static class that can be invoked by using the instance method syntax.


e.g.:

public static class MyAwesomeExtensions
{
       public static int WordCount(this string input)
       {
           return input.Split(' ').Count();
       }
 
 
       public static string Concatenate(this string input, string toAdd)
       {
           return input + toAdd;
       }
 
       public static bool IsNullOrEmpty(this string s)
       {
           return string.IsNullOrEmpty(s);
       }
}


Then, you can use (in the same project or in a project referencing this class):


string s = "This is a test";
int wordCount = s.WordCount();
var something = s.Concatenate(" yeah");

The first parameter of the function, the one with the "this" keyword, specifies what type are you extending.

More on Extension Methods - MSDN