September 2012 - Development Simply Put

A blog simplifies main concepts in IT development and provides tips, hints, advices and some re-usable code. "If you can't explain it simply, you don't understand it well enough" -Albert Einstein

  • Development Simply Put

    If you can't explain it simply, you don't understand it well enough.

    Read More
  • Integrant

    Based in the U.S. with offshore development centers in Jordan and Egypt, Integrant builds quality custom software since 1992. Our staff becomes an extension of your team to eliminate the risks of software development outsourcing and our processes...

    Read More
  • ITWorx

    ITWorx is a global software professional services organization. Headquartered in Egypt, the company offers Portals, Business Intelligence, Enterprise Application Integration and Application Development Outsourcing services to Global 2000 companies.

    Read More
  • Information Technology Institute

    ITI is a leading national institute established in 1993 by the Information and Decision Support Centre.

    Read More

2012-09-14

Interfaces - The Concept

What is the meaning of the word "interface" in English?
If you look up the word "interface" in the dictionary you will find that it can be defined in more than one way as follows:
  • A surface regarded as the common boundary of two bodies, spaces, or phases
  • The facts, problems, considerations, theories, practices, etc., shared by two or more disciplines, procedures, or fields of study: the interface between chemistry and physics
  • A common boundary or interconnection between systems, equipment, concepts, or human beings
  • Communication or interaction: Interface between the parent company and its subsidiaries has never been better
  • A thing or circumstance that enables separate and sometimes incompatible elements to coordinate effectively: The organization serves as an interface between the state government and the public

What is the meaning of "interface" in C#?
Sometimes when you are writing some code, you feel that you need to make your code somehow generic and independent on a single type of objects/classes because you believe that your logic can be applied on wide range of different classes and objects given that these objects share some common features. So, while you are writing your logic, you need to be confident that the class or object you are dealing with and that you don't know its type at the moment of writing your code will not cause any troubles or problems and will undergo the exact logic you want.

To understand what I really mean here, let's try to imagine the scenario below:
  • You want to write a math helper static class which provide some static methods to be used to carry out some mathematical operations
  • One of these operations is comparing two numerical values, if the first value is greater, return +ve int, if equal, return 0, else, return -ve int
  • So, you may write a method to compare two int numbers using the code (intNum1.CompareTo(intNum2))
  • And another method to compare two double numbers using the code (doubleNum1.CompareTo(doubleNum2))
  • And another one to compare two float numbers using the code (floatNum1.CompareTo(floatNum2))
  • And another one to compare two long numbers using the code (longNum1.CompareTo(longNum2))

This will work but this is somehow bad. You feel that this is not what you really needed and imagined when you were thinking of your class. You want to use this class and its helper methods regardless the type of the input because at last it just uses the same logic whatever the input type is given that it has a "CompareTo" member method. Not only the same logic, but also the same line of code except for the type of the numerical value.

Also, why do you need to write the same logic 4 times????? this is not logical and this redundancy in logic and code may cause you problems in the future especially if you decided to apply some changes to the logic.

So, when you analyze the problem, you will find that it would be so great if you are sure that the input type for your method has a member method called "CompareTo" which applies the same logic as it is expected. Then you can apply your logic without any problems and it would be enough to just write one method to apply the logic whatever the input type is.

So, in other words, you need a trustworthy contract between your method and the compiler. This contract will guarantee that the compiler will not by any mean let the user of your class call your one method passing an input type which doesn't have the member method "CompareTo" which applies the same required logic. This way you can apply your logic without any problems.

Also, this way you can make sure that any other class which follows this contract can be passed as an input to your method although you never knew about it before, but your logic can still apply on it.

This contract is the interface :)

So, in IT words, the interface is a contract which guarantees that every class implementing it has some specific member definitions. Note that i said definitions not implementations and that is because two classes can implement the same interface but have different implementations to those members guaranteed by their common interface.

So, if an interface includes into its definition a method with the header "void WriteToLogFile()", then for class A to implement this interface, it should have a member method with the header "public void WriteToLogFile()". Also, for class B to implement this interface, it should have a member method with the header "public void WriteToLogFile()". The implementation of this method in both class A and B may differ.


So, How can we use interfaces in the math helper class?
Without using interfaces, you would have written your method as follows

 public static int CompareValues(int num1, int num2)  
     {  
       return num1.CompareTo(num2);  
     }  
   
     public static int CompareValues(double num1, double num2)  
     {  
       return num1.CompareTo(num2);  
     }  
   
     public static int CompareValues(long num1, long num2)  
     {  
       return num1.CompareTo(num2);  
     }  
   
     public static int CompareValues(float num1, float num2)  
     {  
       return num1.CompareTo(num2);  
     }  

But, after using interfaces, the code will be

 public static int CompareValues(IComparable num1, IComparable num2)  
     {  
       return num1.CompareTo(num2);  
     }  

If you have a look on the "IComparable" interface, you will find its definition as follows:

 // Summary:  
   //   Defines a generalized type-specific comparison method that a value type or  
   //   class implements to order or sort its instances.  
   [ComVisible(true)]  
   public interface IComparable  
   {  
     // Summary:  
     //   Compares the current instance with another object of the same type and returns  
     //   an integer that indicates whether the current instance precedes, follows,  
     //   or occurs in the same position in the sort order as the other object.  
     //  
     // Parameters:  
     //  obj:  
     //   An object to compare with this instance.  
     //  
     // Returns:  
     //   A 32-bit signed integer that indicates the relative order of the objects  
     //   being compared. The return value has these meanings: Value Meaning Less than  
     //   zero This instance is less than obj. Zero This instance is equal to obj.  
     //   Greater than zero This instance is greater than obj.  
     //  
     // Exceptions:  
     //  System.ArgumentException:  
     //   obj is not the same type as this instance.  
     int CompareTo(object obj);  
   }  

This interface defines only a single method with the name "CompareTo", takes input parameter of type object and returns int.

You will find that all of the numerical types (int, double, float, long) implement this interface and that's what we depend on to apply our logic.


What types of members can an interface have?
An interface definition can have:
  1. Method definitions
  2. Property definitions
  3. Event definitions
  4. Indexer definitions
All members of the interface definition should be public. Due to this restriction, it is not allowed to write any access modifiers (public, private, protected, internal, ....) inside an interface definition even if it is public.


So, when do i need to use interfaces?
Interfaces is a concept which can be applied in so many cases and if you know about design patterns you will really embrace the power of interfaces. But, to simplify the whole concept in just few words, interfaces is about "Abstraction rather than Implementation".

This means that, when you design some logic, try to come out with the most abstract meaning and logic of your logic. If you found that your logic could be applied on a group of classes/objects given that they have certain common features or behavior, then you should think of interfaces. But, don't confuse these common features with implementation, they may have different implementation of these common features and you still can apply your logic.

Also, you can write your own interfaces to be used through your system classes/objects to form some kind of contracts to control the way your system classes/objects communicate in a loosely coupled manner. Why?????? because you prefer abstraction to implementation :)


Update:
The new post One Of The Methodologies To Write Clean, Maintainable & Extensible Software is now available including a practical example on how to make use of interfaces.


Anything else?
Yes, there is another concept in C# similar to interfaces called "Abstract Classes" but with some differences.


So, what about "Abstract Classes"?
You will find that always whenever interfaces are mentioned abstract classes are mentioned too with some comparisons between both. But, i didn't do so cause i wanted to address the main concept first which is mainly the same. Once you understand the main concept behind interfaces, it will be so easy to understand abstract classes.


So, now what?
Now, i really encourage you to search and read more about interfaces (and abstract classes) and its applications in design patterns. Then, you will really understand how you can enhance your design and coding skills in a great way using interfaces (and abstract classes).


Finally, i hope this helped you to understand the main concept behind interfaces and its important role in "Abstraction rather than Implementation" concept.

Good Luck :)

2012-09-07

Events & Delegates In C# - Win Forms Controls

I encourage you to first read Events & Delegates In C# - The Concept to understand the main concept of Events & Delegates in C# before starting reading this article.


Assume that you need to make a win forms control to be used by wide range of users for wide range of purposes. This control will include 3 sliders which the control user can move and change their values at rum-time and accordingly an action will happen. This action may be changing a background color or changing volume of a media player or changing values in some fields and so on ... But, the control user should not actually access the 3 sliders inside your control programmatically. It is your responsibility to expose all info and actions that the user can make use of when using your control. So, your control should be as a black box for the user and he can only use and see when you permit him to use and see.

So, you need to make your control raise some sort of events when the sliders are moved telling the control user the new values of the sliders beside which of the 3 sliders has moved. At this point you don't care about how the user will make use of these values cause this is not your concern and it doesn't affect your logic by any mean.

But, before you raise the event, you should tell the control user how he can receive the new sliders value. This is done by defining the delegate which will be connected to your event.

Also, you will need to tell him about the structure of the object/class which you will use to encapsulate the value of the sliders and the name of the moved slider. This is done by defining your custom EventArgs class.

So, now you know the steps we should follow to complete the task, so let's see some code.

Steps:
1. Open visual studio and create a new project of type "Windows Forms Control Library"
2. The name of the project is "WinFormsControlsProject"
3. The name of the solution is "WinFormsControls"
4. Rename the "UserControl.cs" file to "TripleSliders.cs"
5. The solution should now look like the picture below
Events & Delegates In C# - Win Forms Controls
6. Now, drag 3 trackbars and arrange them as in the picture above. Their names are "trackBar1" and "trackBar2" and "trackBar3"
7. Also, drag 3 labels and arrange them as in the picture above
8. Now, we will define our custom eventargs class that we will use to tell the control user which slider has moved and the values of the 3 sliders.
9. So, in the "TripleSliders.cs" file we will write the code below

#region SliderName enum
    public enum SliderName
    {
        Slider1 = 1,
        Slider2 = 2,
        Slider3 = 3
    }
 #endregion

#region EventArgs
    public class SliderPositionChangedEventArgs : EventArgs
    {
        #region Fields & Properties
        SliderName changedSlider;
        public SliderName ChangedSlider
        {
            get { return changedSlider; }
            set { changedSlider = value; }
        }

        int slider1Value;
        public int Slider1Value
        {
            get { return slider1Value; }
            set { slider1Value = value; }
        }

        int slider2Value;
        public int Slider2Value
        {
            get { return slider2Value; }
            set { slider2Value = value; }
        }

        int slider3Value;
        public int Slider3Value
        {
            get { return slider3Value; }
            set { slider3Value = value; }
        }
        #endregion

        #region Constructors
        public SliderPositionChangedEventArgs()
        {
        }
        public SliderPositionChangedEventArgs(SliderName _changedSlider, int _slider1Value, int _slider2Value, int _slider3Value)
        {
            ChangedSlider = _changedSlider;
            Slider1Value = _slider1Value;
            Slider2Value = _slider2Value;
            Slider3Value = _slider3Value;
        }
        #endregion
    }
    #endregion


10. Now, we need to define the delegate to which our event will be related and which will define the header (return type and input parameters) of the method by which the control user will communicate and interact with our control. This method should provide our custom eventargs as an input parameter and could receive a return from the control user if we need so

11. In our case, our control doesn't need to receive any feedback from the control user when he moves any of the sliders. We just raise our event and provide him with the info encapsulated in the custom eventargs. We need nothing after that

12. This means that the method should not have a return type. In other words, it should have "void" as a return type

13. So, up to this moment, we can say that our method should look like this
public void methodname(SliderPositionChangedEventArgs e)

14. But, as a best practice, and as we always see when using .Net controls, the empty method generated when binding to a control event always has an input paramater called "sender" and is of type "object". This "sender" is a reference to the party which raised the event. This is useful because the party which is interested into the event can now have the chance to get a reference to the other party which raised the event in the first place. Sometimes this piece of info can be needed

15. So, to follow the best practice, we will need to update our method header to be like this
public void methodname(object sender, SliderPositionChangedEventArgs e)

16. So, to define a delegate which defines the header above, we will write the line below in the "TripleSliders.cs" file as follows

#region Delegate
    public delegate void SliderPositionChangedEventHandler(object sender, SliderPositionChangedEventArgs e);
 #endregion


17.  Now, we need to define the event which we will raise at some point in our control when a slider is moved. Also, we should somehow relate this event to the delegate we already defined so that when the control user tries to bind to our event the C# compiler will restrict him to write a method with a header matching to the header we defined in the delegate, not any other header

18. Also, note that this event should be a member of our control class. This way, when the control user writes the name of the control instance followed by the "." he will find a member event to bind to using the "+=" operator

19. Also, note that relation between our event and the delegate should somehow be defined. This is done by following the "event" modifier with the name of the delegate we created

20. To do so, we will write the code below inside the "TripleSliders.cs" file inside the class of our control

public partial class TripleSliders : UserControl
    {
        #region Constructor
        public TripleSliders()
        {
            InitializeComponent();
        }
        #endregion

        #region Custom Events
        public event SliderPositionChangedEventHandler SliderPositionChanged;
        #endregion
    }


21. Now, we should be ready to raise our event wherever we want in the code of our control. This is done by calling the event as if we call any other method. Actually, it is not like calling any other method, it is like calling a method having the same header as our delegate and this is logical. Why, because the moment inside our code when we are raising the event, this is the moment when we should provide the info encapsulated in our custom eventargs. So, you can now see the relation between our event and the delegated coming to life

22. So, we can always fire our event by writing the code "SliderPositionChanged(the source, the event args instance encapsulating the changed slider and the values for the 3 sliders)"

23. But, before raising the event, we should check if any other party is bound to our event. This is because it will be useless to raise the event if there is no one interested into knowing that any of the sliders has moved

24. So, how will we check if anything is bound to our event? This is done by checking the value of the event itself. If it is null then nothing is already bound to it at runtime. Otherwise, then something is bound to it

25. So, each time we want to raise the event, we can check if (SliderPositionChanged == null) or not. That is so easy. But, why don't we move this part of logic to a separate method. This method would be called whenever we want to raise the event, whenever it is called, it will check if something is bound to the event and if so it will fire/raise the event. This is a best practice we should follow

26. Also, since this method will be responsible for firing/raising the event, then it should have the same input parameters which the event need

27. So, now we will define a method which will carry out this logic as follows

#region Custom Event Handlers
        public virtual void OnSliderPositionChanged(object sender, SliderPositionChangedEventArgs e)
        {
            if (null != SliderPositionChanged)
            {
                SliderPositionChanged(sender, e);
            }
        }
 #endregion


28. Now, we are so ready to raise our event when we feel we need to. So, according to our logic, we need to fire/raise the event when any of our sliders moves. So, the question here is how we can know if a slider is moved??? Yesssss, we can know that by binding to one of the "trackbar" control built-in events which will be raised by the sliders when they are moved

29. Me myself, i chose to use the "MouseUp" event of the "trackbar" controls for simplicity and to not cause our event to fire for every minor step in the sliders but for the final step when the user release the mouse click when dragging the sliders. Anyway, it is your choice and it depends on your desired logic and design

30. So, I bound to the "MouseUp" events of the three sliders and got three empty methods where i should raise our event passing our custom eventargs class

31, So, inside each of these methods I created an instance of our custom eventargs class "SliderPositionChangedEventArgs", set its properties (moved slider name, value of slider 1, value of slider 2, value of slider 3), called the method responsible for firing the events "OnSliderPositionChanged" passing it the input parameters

32. Doing so, the code looked like this

#region Control Events
        private void trackBar1_MouseUp(object sender, MouseEventArgs e)
        {
            SliderPositionChangedEventArgs args = new SliderPositionChangedEventArgs(SliderName.Slider1, trackBar1.Value, trackBar2.Value, trackBar3.Value);
            OnSliderPositionChanged(this, args);
        }

        private void trackBar2_MouseUp(object sender, MouseEventArgs e)
        {
            SliderPositionChangedEventArgs args = new SliderPositionChangedEventArgs(SliderName.Slider2, trackBar1.Value, trackBar2.Value, trackBar3.Value);
            OnSliderPositionChanged(this, args);
        }

        private void trackBar3_MouseUp(object sender, MouseEventArgs e)
        {
            SliderPositionChangedEventArgs args = new SliderPositionChangedEventArgs(SliderName.Slider3, trackBar1.Value, trackBar2.Value, trackBar3.Value);
            OnSliderPositionChanged(this, args);
        }
 #endregion


33. Now, our control is completed and ready for usage

34. To test our control, I created a test windows forms application project to use our control

35. Create new windows forms application project with the name "TestApp1"

36. Drag and drop our control on the form so that the solution looks like the picture below
Events & Delegates In C# - Win Forms Controls
37. In the form load event I bound our control instance event "SliderPositionChanged" using the "+=" operator and wrote some code in the generated empty method. This code is responsible for changing the form background color according to the values of the 3 sliders in our control

38. So, the code looked like this

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace TestApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            tripleSliders1.SliderPositionChanged += new WinFormsControlsProject.SliderPositionChangedEventHandler(tripleSliders1_SliderPositionChanged);
        }

        void tripleSliders1_SliderPositionChanged(object sender, WinFormsControlsProject.SliderPositionChangedEventArgs e)
        {
            this.BackColor = Color.FromArgb(e.Slider1Value, e.Slider2Value, e.Slider3Value);
        }
    }
}


39. So, when running our test application, here is what happens
Events & Delegates In C# - Win Forms ControlsEvents & Delegates In C# - Win Forms Controls


At last, i wish this helped you understand how to use Events & Delegates in C#. I encourage you to practice using them more and more till you fully understand the main concept.

Good Luck :)


Events & Delegates In C# - The Concept

I encourage you to read Delegates In C# - The Definition article first to understand the main definition of delegates in C#.


The main essence of object oriented programming (OOP) is that it simulates the life we live. Before OOP, the programing approaches were oriented to getting the job done by writing some code to apply some logic. But, OOP was the start point to try to introduce a new approach which is more related and similar to the way we, human beings, live, perform and communicate. That's why when I try to understand a new concept in OOP I first try to find the resemblance which may occur between the concept and the real life I live. So, lets try to find this resemblance in the case we have in our hands, "Events & Delegates in C#".

To fully understand the main concept and behavior of events and delegates in C#, we need to imagine the whole thing as if it is a way by which two or more parties communicate to share info and take actions depending on these info. To do so, let's clear our mind and leave the IT talking aside for a short time.

Imaging that we have a "Teacher" and a "Student". The teacher has a Q & A game to play with the student. The teacher should ask a question and if the student knows the answer he should provide the answer. Then, the teacher should check if the answer is right or wrong and accordingly a score will be calculated.

So, for the game to succeed, both parties, teacher and student, should know the rules to be able to follow the same rules and be on the same page and at last the game should begin. So, for the whole thing to start, there should be 2 stages to follow.

The first stage is "The agreement":
In this stage the teacher tells the student the rules and the student tells the teacher how he will respond and at last they shake hands. So the conversation should be like:
Teacher: When I have a question, I will raise my hand and say; "I have a question".
Student: Ok, and if I want to play, I will ask you for the question and tell you how I will provide the answer (written on paper, by mouth, by mail, .....).
Teacher: Ok, so in this case, I will give you the question and i will get the answer from you by the way you told me about. Then, I will check your answer and update the score.
Student: Ok, that's fine.
Teacher: Ok, then let's start playing.

So, to recap what happened in this stage, we will find that the conversation here is more detailed than the conversations in our real life and that is because eventually we are talking about a development technique and approach which needs both parties in any conversation to be in full control of the info flow leaving nothing to opportunities. So, we already know that this conversation in real life could take only a 2 lines dialogue but here it needs to be more detailed for both parties to know what they will really face in the IT world :)

So, for this stage to complete, we needed to have some main entities:
  1. First party, the conversation initiator .......... teacher
  2. Second party, the responder .......... student
  3. The action by which the initiator will initiate .......... saying "I have a question"
  4. The info provided by the initiator ........... question
  5. The info provided by the responder ........... answer
  6. The way by which the responder will provide the response ........ written on paper, by mouth...
  7. The way by which the initiator will use the response .......... calculation of score

The second stage is "Starting conversation":
At this stage, the game starts as follows:
Teacher: I have a question
Student: Ok, I want to play, please tell me the question and I will write the answer on paper and hand it to you.
Teacher: Ok, the question is "What is your name?". I am waiting for the paper on which you will write your answer. Then i will check the answer and update the score.
Student: Ok, here is the paper including my answer.
Teacher: After checking your answer, I am now updating the score.


Now, lets return to the IT talking.


How can we map this to Events & Delegates in C#?
Now, I think we have an image of what a conversation in C# would look like between two parties. Now let's see how each entity of the conversation (the 7 entities above) will look like into C#.
  1. First party, the conversation initiator .......... teacher ....... The class (A) which will raise an event when certain action takes place
  2. Second party, the responder .......... student .......... Every other class (B, C, ...) wants to be notified when the class A raises its flag
  3. The action by which the initiator will initiate .......... saying "I have a question" ........ The event which the class A will raise
  4. The info provided by the initiator ........... question .......... The info which the class A will provide while raising its event to be used by any listening classes (B, C, ....)
  5. The info provided by the responder ........... answer ......... The info which the class B will provide after processing the info provided by class A
  6. The way by which the responder will provide the response ........ written on paper, by mouth..... The delegate which class B will provide to class A to be executed by class A when the event is raised
  7. The way by which the initiator will use the response .......... calculation of score ......... The logic of class A which will continue after executing the delegate provided by class B

Can you elaborate more?
To recap, what really happens is:

The agreement:
  1. A delegate is defined in scope recognized (referenced) by both Class A and Class B
  2. This delegate defines the header (return type and input parameters) of the method which will be provided by Class B to Class A to be executed by Class A when it raises its event
  3. An event is defined inside Class A to be raised at certain point by the logic of Class A
  4. This event should be mapped to the delegate we already defined before so that it is known that the method that should be provided by Class B should have the header defined by the delegate
  5. A class inheriting from the .Net class "EventArgs" should be defined in scope recognized (referenced) by both Class A and Class B
  6. This class should include some properties encapsulating the info which Class A should provide to Class B while raising the event to be used by Class B inside its delegate if needed
  7. Inside the logic of Class A, the event should be raised when needed
  8. At the line of code where Class A raises the event, Class A can receive the return of the delegate to be used in the rest of the logic if needed
  9. This return value is determined inside the logic of the delegate which is provided by Class B
Starting conversation:
  1. In the main program which can see both Class A and Class B, the events of instances of Class A should be binded to the delegate provided by Class B
  2. Now, whenever every instance of Class A raises its event, the delegate will be executed and a return value will be provided so that the instance of Class A can use this return value in the rest of its logic
 Some notes:
  1. Class A and Class B may not know anything about each other
  2. Class A doesn't know if any other class is interested in its event and the info it provides or not
  3. In the line of code where Class A raises its event, it checks if any class is interested in its event and info or not. If any class is interested, then Class A will wait till the delegate provided by this interested class is executed. Then Class A will receive the return of the delegate and then Class A will complete its logic
  4. The delegate definition which defines the header (return type and input parameters) of the method to be executed by Class A when it raises its event may have no return type, in other words, it may have "void" as its return type. This means that Class A doesn't need any info or feedback from the interested classes

Have we seen any of this logic before in .Net built-in functionality/module?
Yes for sure. you have already seen this while using the windows forms applications controls like the "Button" control. When you add a button to the form and go to the code behind, you will find that the button will have a member called "Click" with the yellow bolt icon beside it in the intellisense menu. This member is the event defined inside the button control/class. Also, you can bind an action to this event using the "+=" operator so that you can fire a certain action/code/logic when the button is clicked at runtime. When you write the "+=" operator and follow it by two tabs, you will find that a line is automatically written after the "+=" operator. This line is "new EventHandler(this.buttonName_Click);". Also, a new empty method is created having the header "void buttonName_Click(Object sender, EventArgs e)".
  • For the "new EventHandler", "EventHandler" is the delegate used to provide the header for the method to be called by the button when it is clicked
  • For "this.buttonName_Click", "buttonName_Click" is the method (which follows the header defined by the delegate "EventHandler") used to provide the implementation/code/logic to be executed when button is clicked
  • For "EventArgs e", "EventArgs" is the class defining the properties encapsulating the info provided by the button itself when it is clicked
  • For the code that will be written inside the empty method, this is the code which will be executed by the button when it is clicked at runtime

Can we see a practical example on how to use Events & Delegates in C#?
Yes, I will provide an example on using Events & Delegates in windows forms applications controls. I will update this article with the link once the new article is ready.
I already created an article on how to use Events & Delegates in Win Forms Controls. You can find it here



At last, I wish this article helped you a bit to understand the whole picture of "Events & Delegates in C#".

Good Luck :)

2012-09-05

Delegates In C# - The Definition


Delegates In C# - The Definition

What does the word "delegate" mean?
The word "delegate" in English means: {A person authorized to act as representative for another; a deputy or an agent} or {A representative to a conference or convention} or {To give a particular job, duty, right, etc. to someone else so that they do it for you}

What does "delegate" mean in C#?
Back from the days of C++, the main concept of delegates existed but with another name; pointer to function.  Actually, the name pointer to function may seem more appropriate and descriptive. When we think of a pointer to function in C#, we may prefer to think of it as a reference to a function. But, these are just some technical words which mean nothing to someone really needs to understand the main concept of delegates. For now, for simplicity, let's think of delegates as if they are the way by which we can postpone thinking of and writing the logic/code of some part/module inside our main code. Why would we need to postpone writing this code ........... wait and see :)

Why do we need "delegates"? What are advantages of using "delegates"?
Using delegates has many advantages but i think the most important ones are:
  • Separation of concerns: Assume you are writing the code for a windows forms user control. This control includes a slider control which will be used to affect gradually something else on the main form when your custom control is dragged and dropped on it. While writing your code of the custom control, all what concerns you is how to manage all aspects of the custom control, how to bind internal events, how to make your custom control resizeable, how to expose some extra properties,......... and so on. But, you are not concerned by any way with how the user will use your control to change the color of the main form background when changing the slider position on your slider, or, how he will use it to raise up the volume of a media player ............. and so on of infinite possibilities of how the user can use your custom control. So, by using delegates, you will separate the concerns to only focus on the logic related to your piece of art, nothing else.
  • Encapsulation: Assume the same example above, when you are writing the code for the same custom control, you can't know exactly how the user will use your control (background color, volume,.....) because you have endless possibilities. Also, it is not logical at all to write your code to only work for one possibility (usage) because you need your custom control to be widely used in different applications and to minimize the restrictions as much as possible. So, by using delegates, you will postpone the logic/code of the action to be taken when the user moves the slider on your custom control ........ the user himself will decide the logic and write this code. Finally, this caused you to encapsulate your piece of art.
When to use delegates?
To answer this question, you need to ask yourself if you are working on a code and you faced some logic you feel that it doesn't belong in your scope or you feel that this logic may differ according to the one who will use your code, or even you. Sometimes, you are both the developer and user of your code, does this mean that you don't need to postpone writing some code using delegates????

What if no stranger will use my code, do I still need to use delegates?
Yes. Sometimes you will need to use delegates even if you are the only user of your code because you don't need your code to be unbalanced and unstable, and the most important is that you need your code to be extendable and maintainable. You should not write some logic and code of some certain module inside a totally different module because this will cost you much time and effort to maintain and while fixing bugs and at some point your code will collapse. So, you need to know how to use delegates in the right place.

When can I use delegates?
There are many cases where you can use delegates some of them you have already seen but didn't recognize. Some of these cases are:
  1. In Windows Forms Applications, .Net built in controls (button, list box, drop down list, ....): In these control you already have been using delegates for a long time. Like when you double click on a button control, you get an empty method where you can write some code to be executed when the button is clicked at run-time. This empty method is a delegate which is fired internally by the button when a user clicks on the button. Imagine if the button control didn't use a delegate to decide the code that it will execute when it is clicked, if this happened then there should have been a button control for every action/code/logic that anyone could need in his application ........... this is impossible and impractical.
  2. Custom controls: You can design your custom control and "delegate" the code that will be executed when users interact with your custom control, you don't have to write a certain static logic.
  3. Libraries: You can write your own library that handle some complicated logic and compile your library into a DLL to be used by all users all around the world. At some point in your code, you will need to write some logic/code which is out of the scope of your library and which can take endless forms. Now, this is the right time to "delegate" this logic to the library user so that he can decide the logic which he sees fitting. Example: a library to sort any type of objects in a list, at some point you will need to compare two object instances in the list to decide which of them is bigger, but you don't know the type of the object while writing your code, also, even if they are of type int, who said that the library user will decide that 1 is bigger than 2? may be he will apply some sort of mathematical operations to compare each two numbers ............. So, anyway, it is not up to you to decide how to compare the elements in the list.
  4. Custom events: When you start using delegates, you will find that they are required when you decide to write your own events for your custom class. This should be understandable because when you write your event you just write a logic to raise a flag when some action happens, but, you don't write the logic/code to be executed when this flag is raised.
  5. Many other applications.
Can I see some code on how to define and use delegates?
Right now this is out of scope of this article but i will try to provide some code on how to use delegates in more than one form. This may be in another article.
I already posted an article on how to use delegates in windows forms applications controls. You can check Events & Delegates In C# - Win Forms Controls


I wish this helped you to understand some of the basic concepts of delegates and I encourage you to search more and read about delegates.

Good Luck :)



2012-09-04

4 Ways To Send Parameters To A C# Method

Actually, the way a parameter can be sent to a method depends on two factors:
  • Type of object/variable to be sent to the method
    • Value type
    • Reference type
  • Way of sending the parameter
    • By value
    • By reference

So, just by guessing, we can say that we have 4 ways to send a parameter to a method. These 4 ways are:
  1. Sending "Value Type", "By Value" ............................... Val By Val
  2. Sending "Value Type", "By Reference" ........................ Val By Ref
  3. Sending "Reference Type", "By Value" ........................ Ref By Val
  4. Sending "Reference Type", "By Reference" ................. Ref By Ref
Some developers mistakenly consider the last two as one ..... hang on and you will know the difference between them.


First, let's point out some important points:
  • We have two types of memories; stack and heap
  • Value types are fully stored in the stack
  • Reference types are partially stored between the stack and heap as follows:
    • A location is reserved in the heap containing the actual value types contained by the reference type
    • A location is reserved in the stack containing the address of the location stated above (in the heap)
  • When sending parameter to a method "By Val", we just send a copy of the actual parameter, not the same parameter instance
  •  When sending parameter to a method "By Ref", we send the same instance of the parameter, not a duplicate copy
  • Applying changes to reference type members differs from applying changes to the reference itself

Second, lets discuss each of the 4 ways;


Val By Val:
This means we are sending a value type by value. In other words, we are sending a copy of a value type (lets say int).

4 Ways To Send Parameters To A C# Method

Since we are sending a copy, then we will copy the value inside the stack location (x) to another location (x') to be eventually used in the call. So, any changes applied inside the method will be applied to this copy (x') and the source value (x) will not be affected at all.

int x = 1;
increment(x);

public void increment(int num)
{
        num++;
}

Value of x will still be equal to 1 because any changes applied inside the method "increment" is applied to a copy of x (x') not x itself


Val By Ref:
This means we are sending a value type by reference. In other words, we are sending the exact value type (lets say int) instance.

4 Ways To Send Parameters To A C# Method
Since we are sending the same exact instance, then the value to be sent to the method will be x and all changes applied inside the method will be applied on x.

int x = 1;
increment(ref x);

public void increment(ref int num)
{
        num++;
}

Value of x will be equal to 2 because any changes applied inside the method "increment" is applied to x itself.


Ref By Val:
This means we are sending a reference type by value. In other words, we are sending a copy of the reference type (lets say employee class).

4 Ways To Send Parameters To A C# Method
Since we are sending a copy, then we will copy the value inside the stack location (x) to another location (x') to be eventually used in the call. So, we will copy the address 1 to a new location in the stack (x'). This means that the new stack location x' will be referencing the same location in the heap as x (because both x and x' hold the same heap location address). So, applying changes on the reference type members (properties like employee name, age, ....) will reflect in the source reference type instance. BUT, applying changes on the reference itself will change the link (address) of x' which makes it point to another heap location leaving the original location as it is.

Employee x = new Employee();
x.Name = "Ahmed";
Rename(x);

public void Rename(Employee emp)
{
        emp.Name = "Tarek";
}

x.Name will be equal to "Tarek" because both x and x' are pointing at the same heap location address sharing the same employee members (Name, Age, .....). So, any changes in x' members reflect in x members.

BUT

Employee x = new Employee();
x.Name = "Ahmed";
Rename(x);

public void Rename(Employee emp)
{
        emp = null;
}

x will not be equal to null and x.Name will be equal to "Ahmed". Why????? because when we set emp = null inside the method, we changed the reference (address) to which the x' is pointing so that at this point x' is pointing to a different heap location than that of x and we can deal with x and x' as two totally different references. So, when x' is set to null, it broke its reference to the heap location but x is still reserving the same reference to the heap location, this means that x is not null.


Ref By Ref:
This means we are sending a reference type by reference. In other words, we are sending the exact reference type (lets say employee class) instance.

4 Ways To Send Parameters To A C# Method

Since we are sending the same exact instance, then we will be sending x to the method and any changes applied to the reference members or the reference itself inside the method will be applied to the reference.

Employee x = new Employee();
x.Name = "Ahmed";
Rename(ref x);

public void Rename(ref Employee emp)
{
        emp.Name = "Tarek";
}

x.Name will be equal to "Tarek" because both x and x' are pointing at the same heap location address sharing the same employee members (Name, Age, .....). So, any changes in x' members reflect in x members.

ALSO

Employee x = new Employee();
x.Name = "Ahmed";
Rename(ref x);

public void Rename(ref Employee emp)
{
        emp = null;
}

x will be equal to null because setting x'=null is totally equivalent to x=null


I wish this cleared up the whole thing for you.
Good Luck :)