HI WELCOME TO Sirees
Showing posts with label c# (c sharp). Show all posts
Showing posts with label c# (c sharp). Show all posts

Understanding Collections and Collections Interfaces

A collection is a set of related objects. Unlike arrays, a collection can grow and shrink dynamically as the number of objects added or deleted. A collection is a class, so you must declare a new collection before you can add elements to that collection.
The .NET Framework provides various collections like ArrayList, HashTable , SortedList, Stack and Queue etc. All these collections are exists in System.Collections namespace.
Class
Description
ArrayList
Represents an array of objects whose size is dynamically increased or decreased as required. It is an alternative to an array. It supports add and remove methods for adding and removing objects from the collection.
Hashtable
Represents a collection of objects which are stored in key/value pair’s fashion, where key is a hash code and value is an object. The key is used to access or manipulates the objects in the collection. It supports add and remove methods for adding and removing objects from the collection.
SortedList
Represents a collection of objects which are stored in key/value pairs fashion like HashTable and can be sorted by the keys. It can accessible by key or by index number. Typically, it a combination of ArrayList and HashTable. It supports add and remove methods for adding and removing objects from the collection.
Stack
Represents a last in, first out (LIFO) collection of objects. It supports push and pop methods for adding and removing objects from the collection.
Queue
Represents a first in, first out (FIFO) collection of objects. It supports Enqueue and Dequeue methods for adding and removing objects from the collection.

Collection Interfaces

All of the collection types use some common interfaces. These common interfaces define the basic functionality for each collection class. The key collections interfaces are – IEnumerable, ICollection, IDictionary and IList.

IEnumerable acts as a base interface for all the collection types that is extended by ICollection. ICollection is further extended by IDictionary and IList.
Interface
Description
IEnumerable
Provides an enumerator which supports a simple iteration over a non-generic collection.
ICollection
Defines size, enumerators and synchronization methods for all nongeneric collections.
IDictionary
Represents a nongeneric collection of key/value pairs.
IList
Represents a non-generic collection of objects that can be individually accessed by index.
All collections interfaces are not implemented by all the collections. It depends on collection nature.
For example, IDictionary interface would be implemented by only those collection classes which support key/value pairs, like HasTable and SortedList etc.
What do you think?
I hope you will enjoy the collections and collections interfaces while programming with C#. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

A Deep Dive into C# Errors or Exceptions Handling

Errors refer to the mistake or faults which occur during program development or execution. If you don't find them and correct them, they cause a program to produce wrong results.

Types of Errors

In programming language errors can be divided into three categories as given below-
  1. Syntax Errors

    Syntax errors occur during development, when you make type mistake in code. For example, instead of writing while, you write WHILE then it will be a syntax error since C# is a case sensitive language.
    1. bool flag=true;
    2.  
    3. WHILE (flag) //syntax error, since c# is case sensitive
    4. {
    5. //TO DO:
    6. }
  2. Runtime Errors (Exceptions)

    Runtime errors occur during execution of the program. These are also called exceptions. This can be caused due to improper user inputs, improper design logic or system errors.
    1. int a = 5, b = 0;
    2. int result = a / b; // DivideByZeroException
  3. Exceptions can be handled by using try-catch blocks.
  4. Logical Errors

    Logic errors occur when the program is written fine but it does not produce desired result. Logic errors are difficult to find because you need to know for sure that the result is wrong
    1. int a = 5, b = 6;
    2. double avg = a + b / 2.0; // logical error, it should be (a + b) / 2.0

Exception Handling

Exception handling is a mechanism to detect and handle run time errors. It is achieved by using Try-Catch-Finally blocks and throw keyword.
  1. Try block

    The try block encloses the statements that might throw an exception.
    1. try
    2. {
    3. // Statements that can cause exception.
    4. }
  2. Catch block

    Catch block handles any exception if one exists.
    1. catch(ExceptionType e)
    2. {
    3. // Statements to handle exception.
    4. }
  3. Finally block

    The finally block can be used for doing any clean-up process like releasing unused resources even if an exception is thrown. For example, disposing database connection.
    1. finally
    2. {
    3. // Statement to clean up.
    4. }
  4. Throw keyword

    This keyword is used to throw an exception explicitly.
    1. catch (Exception e)
    2. {
    3. throw (e);
    4. }

Key points about exceptions handling

  1. Exceptions are types that all directly or indirectly derive from System.Exception class.
  2. Exception objects contain detailed information about the error, such as the state of the call stack and a text description of the error.
  3. A try block is used to throw multiple exceptions that can handle by using multiple catch blocks.
  4. More specialized catch block should come before a generalized one. Otherwise specialized catch block will never be executed.
  5. Exceptions can be explicitly generated by a program by using the throw keyword.
  6. If no exception handling mechanism is used, the program stops executing with an error message.
  7. By providing a catch block without a brackets or arguments, we can catch all exceptions occurred inside a try block.
    1. Catch
    2. {
    3. Console.WriteLine("oException" );
    4. }
  8. By providing a catch block with an exception object, you can obtain more information about the type of exception that occurred.
    1. catch(Exception e)
    2. {
    3. Console.WriteLine(e.Message);
    4. }
  9. The statements inside the finally block are always executed whether exception occurs or not in the program.
  10. Also, before the termination of the program finally block is always executed.

Order of Try-Catch-Finally blocks

In the order of exceptions handling blocks try block comes first, after that catch block(s) come and in the last finally block come.
  1. try
  2. {
  3. // statements that can cause exception.
  4. }
  5. catch (MoreSpecificExceptionType e1)
  6. {
  7. // error handling code
  8. }
  9. catch (SpecificExceptionType e2)
  10. {
  11. // error handling code
  12. }
  13. catch (GeneralExceptionType eN)
  14. {
  15. // error handling code
  16. }
  17. finally
  18. {
  19. // statement to clean up.
  20. }
You can also skip finally block if required.
  1. try
  2. {
  3. // statements that can cause exception.
  4. }
  5. catch (MoreSpecificExceptionType e1)
  6. {
  7. // error handling code
  8. }
  9. catch (SpecificExceptionType e2)
  10. {
  11. // error handling code
  12. }
  13. catch (GeneralExceptionType eN)
  14. {
  15. // error handling code
  16. }
You can also skip catch block(s) if required.
  1. try
  2. {
  3. // statements that can cause exception.
  4. }
  5. finally
  6. {
  7. // statement to clean up.
  8. }
Hence a combination of try-catch-finally or try-catch or try-finally blocks is valid.
What do you think?
I hope you will enjoy the exceptions handling in C# while programming. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

A Deep Dive into C# Abstract Class

Abstract class is a special type of class which cannot be instantiated and acts as a base class for other classes. Abstract class members marked as abstract must be implemented by derived classes.
The purpose of an abstract class is to provide basic or default functionality as well as common functionality that multiple derived classes can share and override.
For example, a class library may define an abstract class that is used as a parameter to many of its functions, and require programmers using that library to provide their own implementation of the class by creating a derived class. In C#, System.IO.FileStream is an implementation of the System.IO.Stream abstract class.
  1. abstract class ShapesClass
  2. {
  3. abstract public int Area();
  4. }
  5. class Square : ShapesClass
  6. {
  7. int side = 0;
  8.  
  9. public Square(int n)
  10. {
  11. side = n;
  12. }
  13. // Override Area method
  14. public override int Area()
  15. {
  16. return side * side;
  17. }
  18. }
  19.  
  20. class Rectangle : ShapesClass
  21. {
  22. int length = 0, width=0;
  23.  
  24. public Rectangle (int length, int width)
  25. {
  26. this.length = length;
  27. this.width = width;
  28. }
  29. // Override Area method
  30. public override int Area()
  31. {
  32. return length * width;
  33. }
  34. }

Features of Abstract Class

  1. An abstract class cannot be instantiated.
  2. An abstract class contain abstract members as well as non-abstract members.
  3. An abstract class cannot be a sealed class because the sealed modifier prevents a class from being inherited and the abstract modifier requires a class to be inherited.
  4. A non-abstract class which is derived from an abstract class must include actual implementations of all the abstract members of parent abstract class.
  5. An abstract class can be inherited from a class and one or more interfaces.
  6. An Abstract class can has access modifiers like private, protected, internal with class members. But abstract members cannot have private access modifier.
  7. An Abstract class can has instance variables (like constants and fields).
  8. An abstract class can has constructors and destructor.
  9. An abstract method is implicitly a virtual method.
  10. Abstract properties behave like abstract methods.
  11. An abstract class cannot be inherited by structures.
  12. An abstract class cannot support multiple inheritance.

Common design guidelines for Abstract Class

  1. Don't define public constructors within abstract class. Since abstract class cannot be instantiate and constructors with public access modifiers provides visibility to the classes which can be instantiated.
  2. Define a protected or an internal constructor within an abstract class. Since a protected constructor allows the base class to do its own initialization when sub-classes are created and an internal constructor can be used to limit concrete implementations of the abstract class to the assembly which contains that class.

When to use

  1. Need to create multiple versions of your component since versioning is not a problem with abstract class. You can add properties or methods to an abstract class without breaking the code and all inheriting classes are automatically updated with the change.
  2. Need to to provide default behaviors as well as common behaviors that multiple derived classes can share and override.
What do you think?
I hope, now you have got everything about abstract class. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.