Solved

Indexers & Delegates

Posted on 2006-06-24
5
371 Views
Last Modified: 2010-04-16
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.
0
Comment
Question by:jedistar
  • 3
5 Comments
 
LVL 52

Accepted Solution

by:
Carl Tawn earned 500 total points
ID: 16978316
An indexer allows you to treat an object a bit like an array using a subscript syntax.
Delegates are basically function pointers. They are used primarily with Events to specify which method to call when an event is fired.

virtual is a modifier applied to members of a base class which allows it to be overridden by a derived class. override is paired with virtual as it is used in a derived class to indicate that you are overriding a virtual method.
new is used to hide a member of a base class. Say you had a class that derived from a third-party class and you added a PaintCircle method to your class. If the third-party at some point added a PaintCircle method to the base class then you would get compiler errors saying that you are hiding a method of the same name in the base class. In this case you would use the "new" keyword to specifiy that you intended to hide the base classes implementation of the method.
0
 

Author Comment

by:jedistar
ID: 16978339
what abt in out ref?
0
 
LVL 52

Expert Comment

by:Carl Tawn
ID: 16978344
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.
0
 
LVL 52

Expert Comment

by:Carl Tawn
ID: 16978354
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.
0
 
LVL 11

Expert Comment

by:vo1d
ID: 16978373
- 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);
        }
    }
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

Suggested Solutions

Article by: Najam
Having new technologies does not mean they will completely replace old components.  Recently I had to create WCF that will be called by VB6 component.  Here I will describe what steps one should follow while doing so, please feel free to post any qu…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now