Using attributes in c#

In the .NET Framework there are many reasons to use attributes, like

  • Defining which classes are serializable
  • Choosing which methods are exposed in a Web service
  • As per definition at MSDN
    Attributes allow us to add descriptions to classes, properties, and methods at design time that can then be examined at runtime via reflection.”

    Consider this example:
    Say you have a class which has a method from older version which is still in use for any reason and now you have come up with a new version of the class which makes fantastic use of Generic List and LINQ and has a new method for similar purpose. You would like developers to prefer the new one provided in the later version of your library. How will you do that ? One way is to write in the documentation. A better way is to use attribute as follow.

    public class AccountsManager
        {
          [Obsolete("prefer GetAccountsList", true)]
          static Account[] GetAccounts( ) { }    
          static List<Account> GetAccountsList( ) { }      
        }
    

    If an obsolete method is used when the program is compiled, the developer gets this info and decides accordingly.

    AccountManager.GetAccounts() is obsolete: prefer GetAccountsList

    We may also create and add Custom Attributes as per requirements.

    References :

  • Use the advantages of custom attributes in your C# applications
  • Using Attributes in C#
  • Implement System.Collections.IList Interface using C#

    Today we will look into the interface System.Collections.IList and some of the its methods. A very good example is for IList implementation in use any class Inheriting from IList or ArraList class itself. Following is ArrayList Signature as on MSDN.

    public class ArrayList : IList, ICollection, IEnumerable, ICloneable
    

    To start with, let’s derive a simple class from IList

    public class ListImpl : IList
    { 
     private object[] _contents = new object[8];
    }
    

    We need to implement all members defined in the IList interface and and the interfaces: ICollection and IEnumerable as IList derives from these interfaces. Following is CopyTo Method from ICollection interface.

            public void CopyTo(Array array, int index)
            {
                int j = index;
                for (int i = 0; i < Count; i++)
                {
                    array.SetValue(_contents[i], j);
                    j++;
                }
            }
    

    Following is GetEnumerator method from IEnumerable interface.

    public IEnumerator GetEnumerator()
    {
      // Refer to the IEnumerator documentation another sample
      return (_contents as IEnumerable).GetEnumerator();
    }
    

    Here are some other methods and properties

          private int _count;
          public int Count
          {
                get
                {
                    return _count;
                }
           }
    
           // Add an object to the List
           public int Add(object value)
           {
               if (_count < _contents.Length)
               {
                   _contents[_count] = value;
                   _count++;
    
                   return (_count - 1);
               }
               else
               {
                    return -1;
               }
           }
    
           // Clear the List
           public void Clear()
            {
                _count = 0;
            }
    
           // Check if the List contains some value
           public bool Contains(object value)
            {
                bool inList = false;
                for (int i = 0; i < Count; i++)
                {
                    if (_contents[i] == value)
                    {
                        inList = true;
                        break;
                    }
                }
                return inList;
            }
    
           // Check if List is fixed size
           public bool IsFixedSize
            {
                get
                {
                    return true;
                }
            }
    
            // Overriding ToString() Method
            public override string ToString()
            {
                StringBuilder sb = new StringBuilder();
                foreach (object o in _contents)
                {
                    sb.Append(o.ToString());
                }
                return sb.ToString();
            }
    

    We need to provide implementation for following methods as per requirements.

    
            public int IndexOf(object value)
            {
                throw new NotImplementedException();
            }
    
            public void Insert(int index, object value)
            {
                throw new NotImplementedException();
            }
    
            public bool IsReadOnly
            {
                get { throw new NotImplementedException(); }
            }
    
            public void Remove(object value)
            {
                throw new NotImplementedException();
            }
    
            public void RemoveAt(int index)
            {
                throw new NotImplementedException();
            }
    
            public object this[int index]
            {
                get
                {
                    throw new NotImplementedException();
                }
                set
                {
                    throw new NotImplementedException();
                }
            }
    
            public bool IsSynchronized
            {
                get { throw new NotImplementedException(); }
            }
    
            public object SyncRoot
            {
                get { throw new NotImplementedException(); }
            }
    

    Working with System.Collections.Stack in C#

    In the last post, Working with System.Collections.Queue, we have seen how to work with Queue using C#. In this article I will explore Stack class and the methods provided.

    Stack, is a simple class which represents last-in, first-out collection (L-I-F-O) of objects and behaves exactly like, any stack in normal life should behave.

    Here is class signature as at MSDN.

    [SerializableAttribute]
    [ComVisibleAttribute(true)]
    public class Stack : ICollection, IEnumerable, 
        ICloneable
    

    Here is how to declare and initialize Stack

               // Dclare Stack
                Stack stack;
    
                // initiatlize with a collection
                stack = new Stack(new int[3] { 1, 2, 3 });
    
                // initiatlize with initial capacity 
                stack = new Stack(10);
    
                // default initialization
                stack = new Stack();
    

    Here is how we can add and remove items from stack. Remember, we can add items at the end and the very last item could be returned or removed. This means that we cannot remove other than the last entry. We can thogh, remove all items at once, we will see how.

               // insert into stack
                stack.Push(6);
                
                // remove from stack
                stack.Pop();
    

    Here are the remaining methods and a bit of details for how to use them.

               // Return an Object at the end (Last input), without removing
                object value = stack.Peek();
    
                // filter and get item as per type from Stack
                IEnumerable queueEnummerable = stack.OfType<string>();
    
                // compare with another object
                bool IsEqualTo = stack.Equals(stack);
    
                // get an instance of type IQueryable
                IQueryable querable = stack.AsQueryable();
    
                // use Cast<T> to convert to another Collection
                List<string> list = stack.Cast<string>().ToList();
    
                // clear a Stack, remove all items
                stack.Clear();
    
                // check if Stack contains an object
                stack.Contains("one");
    
                // copy the contents into an Array
                string[] tempArray = new string[3];
                stack.CopyTo(tempArray, 0);
    
                // get total number of items in Stack
                int numberOfItems = stack.Count;
    
                // Get and use IEnumerator from Stack
                IEnumerator e = stack.GetEnumerator();
                while (e.MoveNext())
                {
                    Object obj = e.Current;
                }
    
                // get type
                stack.GetType();
    
                // convert to an Array of Type T
                stack.ToArray();
    
                // get a string representation
                stack.ToString();
    

    Working with System.Collections.Queue in C#

    In the last post, Working with System.Collections.SortedList, we have seen how to work with SortedList using C#. In this article I will explore Queue class and the methods provided.

    Queue, is a simple class which represents first-in, first-out collection of objects and behaves exactly like, any queue in normal life should behave.

    Here is class signature as at MSDN.

    [SerializableAttribute]
    [ComVisibleAttribute(true)]
    public class Queue : ICollection, IEnumerable, 
        ICloneable
    

    Here is how we can declare and initialize a Queue object

                // declare Queue
                Queue queue;
    
                // initiatlize with initial capacity 
                queue = new Queue(10);
    
                // initiatlize with initial capacity 
                // and grow factor
                queue = new Queue(10, 5);
    
                // initiatlize with a collection
                queue = new Queue(new String[5]);
    
                // default initialization
                queue = new Queue();
    

    This is how to add am object to a Queue. An object could be added to the end only

     // Add an object to the tail
    queue.Enqueue("");
    

    This is how to remove an object from a Queue. An object could be removed from front only

     // remove an object from front
     queue.Dequeue();
    

    Here are remaining methods provided with a bit of details for what they can do for us

                // Return an Object at the front, // without removing
                object value = queue.Peek();
    
                // filter and get item as per type from Queue
                IEnumerable queueEnummerable = queue.OfType<string>();
    
                // compare with another object
                bool IsEqualTo = queue.Equals(queue);
    
                // get an instance of type IQquerable
                IQueryable querable = queue.AsQueryable();
    
                // use Cast<T> to convert to another Collection
                List<string> list = queue.Cast<string>().ToList();
    
                // clear an Queue
                queue.Clear();
    
                // Check if Queue contains an object
                queue.Contains("one");
    
                // copy the contents into an Array
                string[] tempArray = new string[3];
                queue.CopyTo(tempArray, 0);
    
                // get total number of items in Queue
                int numberOfItems = queue.Count;
    
                // Get and use IEnumerator from Queue
                IEnumerator e = queue.GetEnumerator();
                while (e.MoveNext())
                {
                    Object obj = e.Current;
                }
    
                // get type
                queue.GetType();
    
                // convert to an Array of Type T
                queue.ToArray();
    
                // get a string representation
                queue.ToString();