Saturday, November 14, 2015

C# : Part2 [Basics]


As In previous article we have seen few of the pre-defined keywords intricacies like access modifiers, class definitions , parameters, mutable and immutable objects , today let us see other topics like delegates,events and flow control statements

Delegate: is a type that references methods
eg: public delegate void DisplayMessage(string message);

Now we have to declare a variable of this type and make this variable to point to a method which can be static or instance method
-->The method we are going to point should have return type void (i.e same as a delegate) and accepts input parameter  as string

Lets say we have class Display

class Display
 {
    public void showMyMessage(string message)
     {
       Console.WriteLine(message);
     }
 }

Display objDisplay1 = new Display();
Now we can invoke 'showMyMessage''by creating a variable of declared delegate and making it to point to this method as below:

DisplayMessage objDisplayMessage = new DisplayMessage(objDisplay1.showMyMessage);

objDisplayMessage("Hi sudhirr");

Why Delegate : Abstraction , as the end user do not know what is happening and when we expose through services, we can add the invocation list i.e a delegate can invoke any number of methods 
eg: objDisplayMessage +=objDisplay1.showMyMessage;
      objDisplayMessage +=objDisplay2.showMyMessage;

Sometimes we may end up with issues when things like objDisplayMessage =null ; happens any user may send malicious content that can destroy the invocation list , here comes events in to picture where we can attach events (same like delegate but no initialization i.e no chances of making null  )

Events :
Events are variables of type delegate with event keyword.
We can attach events by += and detach events by -=

using event:
btnGo_Click+= buttonclick;
void buttonclick(object sender, RoutedEventArgs e)
{
    objPerson.Name ="Teja";
}
using delegate:

btnGo_Click+=delegate(object sender, RoutedEventArgs e)
{
     objPerson.Name ="Teja";

}

i.e giving inline , creating an anonymous method.

Constructors :
We have static constructors and  Instance constructors.
Static constructors: will have static keyword, there can be only one static const(i.e no overloading ) and it cannot have access modifier on it (For any given type it will be executed only once i.e during run time, even though any numberof times that type  is used or initialized).
-->Static const executes before the instance const.

Just to say: 
public Person()
            : this("Test")
  {

  }
This constructor jus passes the control to the constructor which accepts a string param 

Variable Initializers: 
Generally we do declare instance of a class and assign values to its properties like...
Person objPerson = new Person();
objPerson.Name = "Mahesh";

objPerson.Id = 1;

where variable Initialization is writing code in below way:
Person objPerson = new Person
{
  Name = "Mahesh",
  Id = 1

};

ForEach:
Syntax:  
int[] numbers = { 16, 53, 2, 31, 51, 56, 22, 28, 13, 42 };
foreach (int i in numbers)
{
  Console.WriteLine("Number is " + i);

}

What happens internally :
int[] numbers = { 16, 53, 2, 31, 51, 56, 22, 28, 13, 42 };
IEnumerator ObjEnumerator = numbers.GetEnumerator();
while (ObjEnumerator.MoveNext())
  {
  Console.WriteLine("Number is " + (int)ObjEnumerator.Current);
  }

So to use foreach on objects it should be inherited from IEnumerable, internally to iterate through any object C# calls above code.
If we try to iterate i.e apply foreach on objects that does not inherit from IEnumerable then we get errors like the object does not implement GetEnumerator.

Jumping Statements:
break: same as in switch we use break after a statement in case to come out of switch we use similarly for all other looping statements to come out of that loop(only that loop) and continue exec below code.
continue : Same as break which does not allow to exec code below it and continues with next iteration (whereas break stops any more iterations and comes out of loop )

goto : can skip the lines below it  and go to the set of lines which are mentioned with a label 


foreach (int i in numbers)
 {
   if (i == 53)
   goto DisplayMe;
 }
  DisplayMe:

      Console.WriteLine("My Name");
This diplayMe label may be inside foreach or inside that method, if out side forloop then iteration stops and execution flow continues to next line.

return : Will force to come out of the method, we can use this in void method too with just return;
we can use yield return to return to build a collection i,e IEnumerable Object , i.e build up collection in a lazy manner 

foreach (int n in GetEnumerable())
 {
   Console.WriteLine(n);

 }

public static IEnumerable GetEnumerable()
{
  yield return 10;
  yield return 20;
  yield return 30;
}

we get output 10 20 30  i.e using 'yield return'  will return a collection i.e Ienumerable (Only on which foreach can operate ) but here lazy load implies it will not completely execute GetEnumerable and return values 10,20,30 ata time as collection after returning 10 it will execute what is inside foreach loop and then comes back to where it stopped and continues 

throw : to raise an exception