Link to home
Start Free TrialLog in
Avatar of jedistar
jedistarFlag for Singapore

asked on

Indexers & Delegates

Hi,

I like to know how to use these, and when do i use them in which scenarios require them?

-      Indexers
-      Delegates
-      virtual, new, and override
-      In, out and ref params

Thanks.
ASKER CERTIFIED SOLUTION
Avatar of Carl Tawn
Carl Tawn
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of jedistar

ASKER

what abt in out ref?
In isn't really used as far as I know. out is used with parameters to methods primarily as a mechanism for returning more than one value. ref is used to force value-types to be passed to methods as references so that any change to the value in the method is reflected in the value passed in.
Just to clarify:

When I say that "in" isn't really used, I mean because it is the default for parameters so it is unusual to see it explicitly declared.
- Indexers are used in class, struct or interface, when you wanna access them in a way like arrays.
  Example:
class Program
    {
        public class WeekDays
        {
            private string[] _weekDays = { "Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat" };

            //access to a weekday by method
            public string GetDay(int dayNum)
            {
                return (dayNum < _weekDays.Length ? _weekDays[dayNum] : string.Empty);
            }
     
            //access to a weekday by indexer
            public string this[int dayNum]
            {
                get
                {
                    return (GetDay(dayNum));
                }
            }
        }

       
       
        static void Main(string[] args)
        {            
            WeekDays weekDays = new WeekDays();
           
            string day1 = weekDays.GetDay(0);//get weekday by methodcall
            string day2 = weekDays[1];//get weekday by indexer
           
            Console.ReadKey();
        }              
    }


-A delegate is a type that references a method. Once a delegate is assigned a method, it behaves exactly like that method. The delegate method can be used like any other method, with parameters and a return value. Delegates have to following properties:
   - They are similar to C++ function pointers, but are type safe.
   - They allow methods to be passed as parameters.
   - They can be used to define callback methods.
   - They can be chained together; for example, multiple methods can be called on a single event.
   - Methods don't need to match the delegate signature exactly.

The most common use of delegates are eventhandlers for events.
Example:

        public delegate void ButtonEventHandler();
        class TestButton
        {
            // OnClick is an event, implemented by a delegate ButtonEventHandler.
            public event ButtonEventHandler OnClick;

            // A method that triggers the event:
            private void Click()
            {
                if(OnClick != null)
                {
                    OnClick();
                }
            }
        }

        static void Main(string[] args)
        {            
            TestButton btn = new TestButton();
            btn.OnClick += new ButtonEventHandler(btn_OnClick);
        }

        static void btn_OnClick()
        {
            //do something
        }  


- The virtual keyword is used to modify a method, property, indexer or event declaration, and allow it to be overridden in a derived class.
   By default, methods are non-virtual and you cannot override a non-virtual method. In Addition, you cannot use the virtual modifier with the static, abstract and override modifiers. The new keyword is uses, when you can not override a method, property, indexer or event declaration beacuse it is not marked as virtual.
then you can use the new keyword and make an own implementation.
   
   Example:
   
using System;
class TestClass
{
    public class Dimensions
    {
        public const double PI = Math.PI;
        protected double x, y;
        public Dimensions()
        {
        }
        public Dimensions(double x, double y)
        {
            this.x = x;
            this.y = y;
        }

        public virtual double Area()
        {
            return x * y;
        }
    }

    public class Circle : Dimensions
    {
        public Circle(double r) : base(r, 0)
        {
        }

        public override double Area()
        {
            return PI * x * x;
        }
    }

    class Sphere : Dimensions
    {
        public Sphere(double r) : base(r, 0)
        {
        }

        public override double Area()
        {
            return 4 * PI * x * x;
        }
    }

    class Cylinder : Dimensions
    {
        public Cylinder(double r, double h) : base(r, h)
        {
        }

        public override double Area()
        {
            return 2 * PI * x * x + 2 * PI * x * y;
        }
    }

    static void Main()
    {
        double r = 3.0, h = 5.0;
        Dimensions c = new Circle(r);
        Dimensions s = new Sphere(r);
        Dimensions l = new Cylinder(r, h);
        // Display results:
        Console.WriteLine("Area of Circle   = {0:F2}", c.Area());
        Console.WriteLine("Area of Sphere   = {0:F2}", s.Area());
        Console.WriteLine("Area of Cylinder = {0:F2}", l.Area());
    }
}
   


- The out keyword causes arguments to be passed by reference. This is similar to the ref keyword, except that ref requires that the variable be initialized before being passed. To use an out parameter, both the method definition and the calling method must explicitly use the out keyword.

Example for out:
  static void Method(out int i)
    {
        i = 44;
    }
    static void Main()
    {
        int value;
        Method(out value);
        //value is now 44
    }

Example for ref:

    static void Method(ref int i)
    {
        i = 44;
    }
    static void Main()
    {
        int val = 0;
        Method(ref val);
        //val is now 44
    }
 the in keyword is used for iteration statements.
 Example:
  static void Main(string[] args)
    {
        int[] fibarray = new int[] { 0, 1, 2, 3, 5, 8, 13 };
        foreach(int i in fibarray)
        {
            System.Console.WriteLine(i);
        }
    }