[Last Call] Learn about multicloud storage options and how to improve your company's cloud strategy. Register Now

x
?
Solved

Indexers & Delegates

Posted on 2006-06-24
5
Medium Priority
?
441 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
5 Comments
 
LVL 52

Accepted Solution

by:
Carl Tawn earned 2000 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

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Article by: Ivo
C# And Nullable Types Since 2.0 C# has Nullable(T) Generic Structure. The idea behind is to allow value type objects to have null values just like reference types have. This concerns scenarios where not all data sources have values (like a databa…
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
This course is ideal for IT System Administrators working with VMware vSphere and its associated products in their company infrastructure. This course teaches you how to install and maintain this virtualization technology to store data, prevent vuln…
In this video, Percona Solution Engineer Rick Golba discuss how (and why) you implement high availability in a database environment. To discuss how Percona Consulting can help with your design and architecture needs for your database and infrastr…
Suggested Courses

650 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