Wednesday, March 14, 2012

Basics of .NET Collections in C#

Introduction

This article focuses on managing collections in .NET Framework 2.0. Collection represents a set of objects that you can access by stepping through each element in turn. The .NET Framework provides specialized classes for managing collection and these classes have rich capability for enhancing your programming experience through better performance and easy maintenance.

Object class is the base class of every type in .NET. All the collections implement IEnumerable interface that is extended by ICollection interface. IDictionary and IList are also interfaces for collection which are derived from ICollection as shown in the diagram.



System.Object

Object class is the base class of every type. All other types directly or indirectly derive from object class. Because of its lofty position, a .NET developer should have a good knowledge of the object class and its members.

  1. Static Methods

     
    object.Equals(object objA, object objB) 

     This method does some testing for null on objA and objB and calls objA.Equals(objB). It returns true if objA and objB are null references or both are the same instance, or if objA.Equals(objB) returns true, otherwise it returns false.


 int n1 = 2;
 int n2 = 3;
 bool result1 = object.Equals(n1, n2); 
 // returns false.
 // because n1 & n2 are value type 
 // and it will be compared by value. 
 
 
 string s1 = "test";
 string s2 = "test";
 bool result2 = object.Equals(s1, s2); 
 
// returns true. s1 & s2 are 
// reference type,
// but Equals(object obj) method of 
// object class is overridden by 
// string class.
// that's why it returns true because 
// s1 and s2 are comparing 
// by their values.
   
 object obj1 = new Person(1, "Test1");
 object obj2 = new Person(1, "Test1");
 bool result3 = object.Equals(obj1, obj2); 
 
// returns false. obj1 & obj2 
// are reference type,
// both are comparing by 
// reference and both are 
// different instances but 
// having same values.





No comments:

Post a Comment