Click here to hide categories Click here to show left categories

User: Home          welcome : Guest          Log In / Register here     




QuestPond’s Interview Questions & Answers on .NET

What are indexers?

Indexers let us individual objects like a collections.

Consider the following example where we have a composition relationship between customer and address class.

public class Customer
{
	public string CustomerName{ get; set; }
	public string Address{ get; set; }
	private List
Addresses; } public class Address { publicpublic string City{get;set;} public string City{get;set;} }

Now usually in order to access the address object, some functions will be exposed by customer class as follows.

public List
GetAddersses() { return Addresses; } public Address GetAddressAtIndex(int Index) { return Addresses[Index]; } public Addres GetAddressByCity(string CityName) { foreach(Address a2 in Addresses) { If(a2.CityName==cityName) { return a2; } } }

In the client code one of these functions will be invoked using customer class object

Address a=MyCustomer.GetCustomerByCity(“Mumbai”);

Now indexers let us treat our customer object as collection and it will return address objects on passing some parameters.

We will create indexer inside Customer Class as follows,

public class Customer
{
	.
	.
	.
	public Address this[string CustomerName]
	{
		get
		{
			foreach(Address a2 in Addresses)
			{
				If(a2.CityName==cityName)
				{
					return a2;
				}
			}

		}
	}
}

Now we can use the following syntax and get the Address object.

Address a=MyCustomer[“Mumbai”];

Don’t forget to subscribe us on Facebook for constant updates.

For technical trainings on various topics like WCF(Windows Communication Foundation), MVC, Business Intelligence, Design Patterns, WPF, TFS and Basic fundamentals feel free to contact SukeshMarla@Gmail.com or visit www.sukesh-marla.com

For more stuff like this, click here. Subscribe to article updates or follow at twitter @SukeshMarla

See following video on indexers in C# (Csharp): -

Click and see here for more .NET training.





Helpful Website Url
http://www.questpond.com/
Share this article   |    Print    |    Article read by 3662 times
Author:
Shivprasad koirala Koirala
I am a Microsoft MVP for ASP/ASP.NET and currently a CEO of a small E-learning company in India. We are very much active in making training videos , writing books and corporate trainings. Do visit my site http://www.questpond.com for .NET, C# , design pattern , WCF , Silverlight , LINQ , ASP.NET , ADO.NET , Sharepoint , UML , SQL Server training and Interview questions and answers
Related Articles:
Related Interview Questions: