Pages

Monday, May 28, 2012


Delegates

A delegate in C# is similar to a function pointer in C or C++. Delegate allows the programmer to encapsulate a reference to a method inside a delegate object. The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked. Unlike function pointers in C or C++, delegates are object-oriented, type-safe, and secure.

A delegate is defined with a specific signature (return type, parameter type and order etc). To invoke a delegate object, one or more methods are required with the EXACT same signature. A delegate object is first created similar like a class object created. The delegate object will basically hold a reference of a function which has the same signature.

 

Syntax for Declaring a Delegate:

Public delegate <return type> <Delegate Name> (parameters);

Example: public delegate int Calculate (int x, int y);

We can use the delegates with out parameters also.

Delegates are of 2 types
1)     Single Cast Delegate
2)      Multi Cast  Delegate

Single Cast Delegate: It is a delegate which holds the reference of one method.
Example program for Single cast delegate

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BloggerExamples
{
    //delegate declaration with two parameters integers.
    public delegate int MyDelegate(int x, int y);
    class SingleDelegateExample
    {
        public static int Add(int x, int y)
        {

            return x + y;

        }

        static void Main(string[] args)
        {
            MyDelegate del1 = new MyDelegate(Add);
            int addResult = del1(5, 5);
            Console.WriteLine("5 + 5 = {0}\n", addResult);
            Console.ReadLine();
        }
}

Multi Cast Delegate: It is a delegate which holds the reference of more than one method.

Delegate's multicast means that a delegate object can maintain a list of methods to call, rather than a single method.

If you want to add a method to the invocation list of a delegate object, you simply make use of the overloaded += operator, and if you want to remove a method from the invocation list you make use of the overloaded operator -=.

In Multi-casting you create a single delegate that will invoke multiple encapsulated methods. The return type of all the delegates should be same.

Note:  The question why are we using Multi-cast delegates when Single-cast delegates are enough?
 
Answer to this question is that if we want to call three methods when a button is clicked. In this situation we use the Multi-cast delegates instead of single cast delegate why because single cast can hold the reference of only one method. But Multi cast delegate can hold references of multiple methods 

The Multi-cast delegates are used with events where multiple calls to different methods are required.

The following program will demonstrate the Multi cast Delegate

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace Blogger Examples
{
    //delegate declaration with two parameters integers
    public delegate void MulticastDelegate(int x, int y);
    class MyMulticastDelegate
    {
        Public static void Add (int x, int y)
        {

            Console.WriteLine ("You are in Add () Method");

            Console.WriteLine ("{0} + {1} = {2}\n", x, y, x + y);

        }

        public static void Multiply (int x, int y)
        {

            Console.WriteLine ("You are in multiply () Method");

            Console.WriteLine("{0} X {1} = {2}", x, y, x * y);

        }

        static void Main(string[] args)
        {
            MulticastDelegate del = new MulticastDelegate (Add);
            del += new MulticastDelegate(Multiply);
            Console.WriteLine ("****calling Add() and Multiply() Methods.****\n\n");

            del(5, 5);
            del -= new MulticastDelegate(Add);

            Console.WriteLine("\n\n****Add() Method removed.****\n\n");
            del(5, 5);
            Console.ReadLine();
        }
    }
}

OutPut:


Thursday, May 10, 2012


Progress Bar:

In this article I am going to explain how to create and use Progress Bar Control

A Progress Bar control is used to represent the progress of a lengthy operation that takes time where a user has to wait for the operation to be finished.

Properties:
                        
The Following are the important properties of Progress Bar. Those are

1.      Minimum. This property obtains or sets the lower value for the range of valid values   for progress. The default value of this property is zero (0); you cannot set this property to a negative value
2.      Maximum. This property obtains or sets the upper value for the range of valid values for progress. The default value of this property is 100.
3.      Value. This property obtains or sets the current level of progress. The value must be in the range that the Minimum and the Maximum properties define.
4.      ProgressBarColor. This property obtains or sets the color of the progress bar.
5.      RightToLeftLayout Progress Bar control can also show the progress from right to left by setting RightToLeftLayout to true(default is left to right)
6.      MarqueeAnimationSpeed property represents the time period, in milliseconds, that it takes the progress block to scroll across the progress bar.


Creating a Progress Bar:

We can create the Progress Bar in two ways
1)      At Design Time.
2)      At Run Time.

At Design Time:

To create the Progress bar at design time, select Progress Bar from the tool box and drag it into form. Then it looks like below.

At Run Time:

To Create the Progress Bar at run time, use Progress Bar Class.  Create an instance to this class, set it properties and add it to the form.

First create a instance to the class

ProgressBar PBar1 = new ProgressBar();

Then set it required properties. The following code demonstrate how to set the value of its properties.


PBar1.Location = new System.Drawing.Point(20, 20);
PBar1.Width  = 300;
PBar1.Height = 50;
PBar1.Maximum = 1000;

But in desing time we can set the properties of Progress Bar by opening the properties window using F4 or right click on control, go to properties

Adding to Form

Controls.Add(PBar1);



Wednesday, May 9, 2012


Context Menu Strip:

C# context menu strips are the menus that pop up when the user clicks with the right hand mouse button over a control or area in a Windows based form. They are called context menus because the menu is usually specific to the object over which the mouse was clicked. Context menus are also sometimes referred to as Popup Menus or Shortcut menus.


Now I am going to explain how to add context strip to our form and how to add events to that menu items using an example.

Example program:

Steps:
1)      Open a windows application.
2)      Drag the Context strip menu from tool box into form
3)      Double Click on Context Menu Strip  and enter the text in the available box on form as shown below

4)      Enter number menu items u want add for that context menu strip. In this example I am adding 4 items those are 1) add 2) Sub 3) Clear 4) Exit.
5)      Add three text boxes and labels as look like below.
6)      Open the Form Properties (by right click with mouse and select properties). Select Context Menu Strip Property and select ContextMenuStrip1 from drop down list.
7)      To write the code for menu items Double Click on each item and write the following code in event handlers.


  private void addToolStripMenuItem_Click(object sender, EventArgs e)
 {
   int result = int.Parse(textBox1.Text) +    int.Parse(textBox2.Text);
   textBox3.Text = Convert.ToString(result);
 }

private void subToolStripMenuItem_Click(object sender, EventArgs e)
 {
    int result = int.Parse(textBox1.Text) - int.Parse(textBox2.Text);
    textBox3.Text = Convert.ToString(result);
 }

  private void xToolStripMenuItem_Click(object sender, EventArgs e)
  {
            textBox1.Text = "";
            textBox2.Text = "";
            textBox3.Text = "";
  }

  private void exitToolStripMenuItem1_Click(object sender, EventArgs e)
  {
            Application.Exit();
  }   

OutPut:
Reason for Output:

1)      Entered 100 in text box1
2)      Entered 200 in text box2
3)      Selected Add from Context Menu Strip.
4)      Result 300  is displayed in text box3


  

Monday, May 7, 2012


Color Dialog:

Color dialog Control is Pallet of colors. This Control is used to select any color from available colors and also used to define the custom colors.  A typical color Dialog control is looks like below.

The only purpose of color dialog control is to display the available colors and to create the custom colors and apply those colors to our application.

Creating a colorDialog Control:

 We can create a color dialog control in two ways, those are
1)      Using Forms Designer at design time
2)      Using ColorDialog Control at run time.


Design Time:

To create a ColorDialog control at design-time, you simply drag and drop a ColorDialog control from Toolbox to a Form. 

Run time:

 To create a Color Dialog At run time, you simple create the instance for ColorDialog class. Call the ShowDialog method to display the color dialog

  Syntax: ColorDialog colordlg1 = new ColorDialog ();


Setting ColorDialog Properties:

Open the properties window by pressing F4 or right click on a control and select Properties menu item. It looks like below 


AllowFullOpen:

We can create custom define colors only when this property is true only. If this property is false, we can use only available colors.

When this property is true – define Custom colors option will be enabled where you can define your required color by selecting color form colors area or by setting RGB values.



When this property is false - define Custom colors option will be disabled



Example program:

Create an application that changes form back  ground color and button fore ground color

  
Steps:

1)      Open Windows application.
2)      Drag a button on form.
3)      Double click on the button and write following code in button1 _click event.

    private void button1_Click(object sender, EventArgs e)
     {

            ColorDialog clrDlg = new ColorDialog();
            clrDlg.ShowDialog();
            button1.ForeColor = clrDlg.Color;
            this.BackColor = clrDlg.Color;

  }

OutPut:

    When user selects the Green Color form ColorDialog box, output will be as below






Friday, May 4, 2012



Boxing And UnBoxing:

In this Article, I am going to explain the concept of Boxing and UnBoxing. This is one of type casting technique

              C# provides us value types and reference types. Converting value type to reference is called as Boxing. Converting from reference type to value type is called UnBoxing.

With this concept we can link between value types and reference types by converting value type to reference type and vice-versa.

Value types:

Value type variables directly contain their values. All value types are stored in stack and derived from System.ValueType. Structures and enum also derived form System.ValueType and stored in stack so those are also called Value Types.

Value types are primitive types those re aliases of the .NET Framework System types. For example, int  is an alias of System.Int32

Example: System.ValueType x = 10;

When we compile this line of code, compiler will takes x as of System.Int32 by default.

Reference Types:
Reference type variables store the address of the data. All reference types are stored in heap and derived from System. Object. All classes are reference types.
Because reference types represent the address of the data rather than the data itself, assigning a reference variable to another doesn’t copy the data. Instead, assigning a reference variable to another instance creates a second copy of the reference, which refers to the same location of the heap as the original value:
Boxing:

While boxing any value from value type to reference type, we can do implicit or explicit casting. Implicit boxing means you no need to inform the complier that you are boxing from value type to object. Right Now I am giving below example for “Implicit Typecasting

Ex:   int x = 30;
       Object o = x;
       Console.writeline (“Object value after boxing {0}”, o) // prints 30

      // Explicit Typecasting…
      Int y = 50;
      Object e = (Object) y;
      Console.WriteLine (“Object value after typecasting {0}”, e) // prints 50

UnBoxing:

Let we see how to do un Boxing. While converting the reference type to value type, we cannot use the implicit type casting. To do Unboxing any reference value we must use the explicit type casing only. See the below example.

Ex:  int x = 5;
       Object o1 = x; //boxing
       Int y = o1; // gives error
       Int y = (int) o1; //
       Console.WriteLine (“y value after unboxing.. {0}”, y); // prints 5


For an unboxing conversion to a given value-type to succeed at run-time, the value of the source argument must be a reference to an object that was previously created by boxing a value of that value-type.

  Ex: int32 x = 10;
       Object ob1 = x; //boxing
       Int64 y;
       y = (int) ob1; // unboxing
      
This code complies successfully but while executing, gives InvalidCastException. So the type variable used for boxing will be same when unboxing the value