Interface
An interface is a contract: the guy writing the interface say "hey, I accept things looking that way", and the guy using the interface say "OK, the class I write looks that way".
And interface is an empty shell, there are only the signatures (name / params / return type) of the methods. The methods do not contain anything. The interface can't do anything. It's just a pattern.
E.G (pseudo code):
// I say all motor vehicles should look like that :
interface MotorVehicle
{
    void run();

    int getFuel();
}
// my team mate complies and write vehicle looking that way
class Car implements MotoVehicle
{

    int fuel;

    void run()
    {
        print("Wrroooooooom");
    }


    int getFuel()
    {
        return this.fuel;
    }
}
Implementing an interface consume very little CPU, because it's not a class, just a bunch of names, and therefor there is no expensive lookup to do. It's great when it matters such as in embedded devices.
Abstract classes
Abstract classes, unlike interfaces, are classes. There are more expensive to use because there is a lookup to do when you inherit from them.
Abstract classes look a lot like interfaces, but they have something more : you can define a behavior for them. It's more about a guy saying "these classes should look like that, and they got that in common, so fill in the blanks !".
e.g:
// I say all motor vehicles should look like that :
abstract class MotorVehicle
{

    int fuel;

    // they ALL have fuel, so why let others implement that ?
    // let's make it for everybody
    int getFuel()
    {
         return this.fuel;
    }

    // that can be very different, force them to provide their
    // implementation
    abstract void run();

}
// my team mate complies and write vehicle looking that way
class Car extends MotorVehicule
{
    void run()
    {
        print("Wrroooooooom");
    }
}

Interface:
Every single Method declared in an Interface will have to be implemented in the subclass. Only Events, Delegates, Properties (C#) and Methods can exist in a Interface. A class can implement multiple Interfaces.

Abstract Class Only Abstract methods have to be implemented by the subclass. An Abstract class can have normal methods with implementations. Abstract class can also have class variables beside Events, Delegates, Properties and Methods. A class can only implement one abstract class only due non-existence of Multi-inheritance in C#.

  • interfaces can have no state or implementation
  • a class that implements an interface must provide an implementation of all the methods of that interface
  • abstract classes may contain state (data members) and/or implementation (methods)
  • abstract classes can be inherited without implementing the abstract methods (though such a derived class is abstract itslef)
  • interfaces may be multiple-inherited, abstract classes may not (this is probably the key concrete reason for interfaces to exist separately from abtract classes - they permit an implementation of multiple inheritance that removes many of the problems of general MI).

QUESTIONS:
  1. What is the point of creating a class that can't be instantiated?
  2. Why would anybody want such a class?
  3. What is the situation in which abstract classes become NECESSARY?
  1. most commonly to serve as a base-class or interface (some languages have a separate interface construct, some don't) - it doesn't know the implementation (that is to be provided by the subclasses / implementing classes)
  2. abstraction and re-use
  3. when the base-class can provide no meaningful default-implementation for a method (but allowing subclasses to re-use the non-abstract parts of the implementation; any fields, non-abstract methods, etc)


That interview question reflects a certain belief of the person asking the question. I believe that the person is wrong, and therefore you can go one of two directions.
  1. Give them the answer they want.
  2. Respectfully disagree.
The answer that they want, well, the other posters have highlighted those incredibly well. Multiple interface inheritance, the inheritance forces the class to make implementation choices, interfaces can be changed easier.
However, if you create a compelling (and correct) argument in your disagreement, then the interviewer might take note. First, highlight the positive things about interfaces, this is a MUST. Secondly, I would say that interfaces are better in many scenarios, but they also lead to code duplication which is a negative thing. If you have a wide array of subclasses which will be doing largely the same implementation, plus extra functionality, then you might want an abstract class. It allows you to have many similar objects with fine grained detail, whereas with only interfaces, you must have many distinct objects with almost duplicate code.
Interfaces have many uses, and there is a compelling reason to believe they are 'better'. However you should always be using the correct tool for the job, and that means that you can't write off abstract classes.

In C#, interfaces are distinct from classes (even abstract classes);
  • interfaces can only define the API (method signatures, event declarations, property declarations), not the implementation (fields, method bodies, etc)
  • you can only inherit one base class, but you can implement multiple interfaces
But they have similarities in some usages - for example when used in an abstract factory implementation.

Let's take your example of a Dog and a Cat class, and let's illustrate using C#:

Both a dog and a cat are animals, specifically, quadruped mammals (animals are waaay too general). Let us assume that you have an abstract class Mammal, for both of them:

public abstract class Mammal

This base class will probably have default methods such as:

* Hunt
* Feed
* Mate

All of which are behavior that have more or less the same implementation between either species. To define this you will have:

public class Dog : Mammal
public class Cat : Mammal

Now let's suppose there are other mammals, which we will usually see in a zoo:

public class Giraffe : Mammal
public class Rhinoceros : Mammal
public class Hippopotamus : Mammal

This will still be valid because at the core of the functionality, Hunt(), Feed() and Mate() will still be the same.

However, giraffes, rhinoceros, and hippos are not exactly animals that you can make pets out of. That's where an interface will be useful:

public interface IPettable
{
IList Tricks{get; set;}
void Bathe();
void Train(Trick t);
}

The implementation for the above contract will not be the same between a cat and dog; putting their implementations in an abstract class to inherit will be a bad idea.

Your Dog and Cat definitions should now look like:

public class Dog : Mammal, IPettable
public class Cat : Mammal, IPettable

Theoretically you can override them from a higher base class, but essentially an interface allows you to add on only the things you need unto a class without the need for inheritance.

Consequently, because you can usually only inherit from one abstract class (in most statically typed OO languages that is... exceptions include C++) but be able to implement multiple interfaces, it allows you to construct objects in a strictly as required basis.
link|edit|flag



Friday, April 16, 2010

Exception Handling in C#

"EXCEPTION IS A RUNTIME ERROR WHICH ARISES BECAUSE OF ABNORMAL CONDITION IN A CODE SEQUENCE. "

The try block contains the code segment expected to raise an exception. This block is executed until an exception is thrown The catch block contains the exception handler. This block catches the exception and executes the code written in the block. If we do not know what kind of exception is going to be thrown we can simply omit the type of exception.  

The finally block is used to do all the clean up code. It does not support the error message, but all the code contained in the finally block is executed after the exception is raised. We can use this block along with try...catch and only with catch too. The finally block is executed even if the error is raised. Control is always passed to the finally block regardless of how the try blocks exits.


There are a number of exception classes provided by C#, all of which inherit from the System.Exception class. Following are some common exception classes:

  • Exception Class - - Cause
  • SystemException - A failed run-time check;used as a base class for other.
  • AccessException - Failure to access a type member, such as a method or field.
  • ArgumentException - An argument to a method was invalid.
  • ArgumentNullException - A null argument was passed to a method that doesn't accept it.
  • ArgumentOutOfRangeException - Argument value is out of range.
  • ArithmeticException - Arithmetic over - or underflow has occurred.
  • ArrayTypeMismatchException - Attempt to store the wrong type of object in an array.
  • BadImageFormatException - Image is in the wrong format.
  • CoreException - Base class for exceptions thrown by the runtime.
  • DivideByZeroException - An attempt was made to divide by zero.
  • FormatException - The format of an argument is wrong.
  • IndexOutOfRangeException - An array index is out of bounds.
  • InvalidCastExpression - An attempt was made to cast to an invalid class.
  • InvalidOperationException - A method was called at an invalid time.
  • MissingMemberException - An invalid version of a DLL was accessed.
  • NotFiniteNumberException - A number is not valid.
  • NotSupportedException - Indicates sthat a method is not implemented by a class.
  • NullReferenceException - Attempt to use an unassigned reference.
  • OutOfMemoryException - Not enough memory to continue execution.
  • StackOverflowException - A stack has overflown.

Now you have added the connection string in the web.config file. Let's see some code that we can use to access the database. We want to load some data from the database when the page is loaded for the first time.

private void Page_Load(object sender, System.EventArgs e)
{
if(!Page.IsPostBack)
{
string connectionString = (string) ConfigurationSettings.AppSettings["ConnectionString"];
SqlConnection myConnection = new SqlConnection(connectionString);
SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM Categories",myConnection);
DataSet ds = new DataSet();
ad.Fill(ds,"Categories");
myDataGrid.DataSource = ds;
myDataGrid.DataBind();
}
}

First, we check that if it's not a postback we load data. For this example to work you need to add the namespace:
using System.Configuration;

Let's see what is going on here:
1) string connectionString receives the string from the web.config file which is referred by the "ConnectionString" key we set in the web.config file.
2) We make the object of the SqlConnection class which deals with SQL Server databases.
3) We made the data adapter object. Data adapter is a kind of connection to the database. In the data adapter object we specify that what we want from the database. In this case we want all the rows of the Categories table.

NOTE:
Always use stored procedures for accessing the data. Accessing or running Ad-hoc queries are dangerous as they are open for SQL Injections.
4) Next we made an instance of the DataSet class. DataSet will contain the result of the SqlDataAdapter even if the database connection is not made.
5) Later, we filled the dataset with the data using dataadapter.
6) And finally we assigns the datagrid to the dataset and binds it on the screen.
Pretty simple right?

Lets see if we can improve the code above:

private void Page_Load(object sender, System.EventArgs e)
{
if(!Page.IsPostBack)
{
string connectionString = (string) ConfigurationSettings.AppSettings["ConnectionString"];
SqlConnection myConnection = new SqlConnection(connectionString);
SqlDataReader reader = null;
SqlCommand myCommand = new SqlCommand("GetData",myConnection);
myCommand.CommandType = CommandType.StoredProcedure;
try
{
myConnection.Open();
reader = myCommand.ExecuteReader();
myDataGrid.DataSource = reader;
myDataGrid.DataBind();
}
catch(Exception ex)
{
// Catches and logs the exception
}
finally
{
reader.Close();
myConnection.Close();
}


In the code above we are using the SqlCommand object and stored procedure. You might have noted SqlDataReader, if you want to merely iterate through the database rows and select them its best to use SqlDataReader since its much faster than DataSet.

Finally we catch exceptions if any of them are generated and closes the connection.

Value Types
Value types include the following:

  • All numeric data types
  • Boolean, Char, and Date
  • All structures, even if their members are reference types
  • Enumerations, since their underlying type is always SByte, Short, Integer, Long, Byte, UShort, UInteger, or ULong

Reference Types
Reference types include the following:
  • String
  • All arrays, even if their elements are value types
  • Class types, such as Form
  • Delegates

Elements That Are Not Types
The following programming elements do not qualify as types, because you cannot specify any of them as a data type for a declared element:
  • Namespaces
  • Modules
  • Events
  • Properties and procedures
  • Variables, constants, and fields



An example

This example shows the difference between how a value type works in memory, and how a reference does. First we define a new Value Type and a new Reference Type.
class ReferenceType
{
   public Int32 X;
} 

 
struct ValueType
{
   public Int32 X;
}
Now we want to use these types to show how they work:
ReferenceType ref1 = new ReferenceType();

ValueType val1     = new ValueType()
 
ref1.X = 5
val1.X = 5;
The layout of the memory at this point looks something like the following:

 If we now make copies of these values using the following code:
ReferenceType ref2 = ref1;
ValueType val2 = val1;
The layout of the memory now looks something like the following:
 If we now change the value of each of the new copies using the following code:
Ref2.X = 8;
Val2.X = 8;
The layout of the memory now looks something like the following:
Summary
  • A variable that is of type value directly contains a value. Assigning a variable of type value to another variable of type value COPIES that value.
  • A variable of type reference, points to a place in memory where the actual object is contained. Assigning a variable of type reference to another variable of type reference copies that reference (it tells the new object where the place in memory is), but does not make a copy of the object.

  • Value types are stored on the stack.
  • Reference types are stored on the heap.

  • Value types can not contain the value null. *
  • Reference types can contain the value null.

  • Value types have a default implied constructor that initializes the default value.
  • Reference types default to a null reference in memory.

  • Value types derive from System.ValueType.
  • Reference types derive from System.Object.

  • Value types cannot derive a new type from an existing value type, but they are able to implement interfaces.
  • Reference types can derive a new type from an existing reference type as well as being able to implement interfaces.

  • Changing the value of one value type does not affect the value of another value type.
  • Changing the value of one reference type MAY change the value of another reference type.

  • The nullable type (only in .NET 2.0) can be assigned the value null.








Nullable in .Net 2.0, helps to determine whether variable has been assigned a value or not. Example: Quiz application having option yes/no, but it should displayed “Not Attempted” when user does not make any choice. This will work for both Data types and data base nullables values.NameSpace use for this purpose is system.nullable.
 
In .Net Framework 2.0, value types can be extended to take either their normal values or a null value. Such an extension is called a nullable type.

Declaring a variable as nullable enables the HasValue and Value members.

Nullable b = null; 

-OR-
// Shorthand notation for declaring nullable type, only for C#

bool? b = null;



Example of Nullable Type
Use HasValue to detect whether or not a value has been set:

if (b.HasValue)
Console.WriteLine("User has Attempted Given Question");
else
Console.WriteLine("User has not Attempted Given Question");

Output
User has not Attempted Given Question


C# 2.0 allows you to assign null values to premitive types such as int, long, and bool. The following code shows how to define an integer as nullable type and checks if the value of the integer is null or not.

Nullable types


public static void TestNullableTypes()
{
// Syntax to define nullable types
int? counter;
counter = 100;
if (counter != null)
{
// Assign null to an integer type
counter = null;
Console.WriteLine("Counter assigned null.");
}
else
{
Console.WriteLine("Counter cannot be assigned null.");
Console.ReadLine();
}
If you remove the "?" from int? counter, you will see a warning as following: "Cannot convert null to int besause it is a value type "

Nullable types have the following characteristics:
  • Nullable types represent value-type variables that can be assigned the value of null. You cannot create a nullable type based on a reference type. (Reference types already support the null value.)
  • The syntax T? is shorthand for System.Nullable, where T is a value type. The two forms are interchangeable.
  • Assign a value to a nullable type in the same way as for an ordinary value type, for example int? x = 10; or double? d = 4.108;
  • Use the System.Nullable.GetValueOrDefault property to return either the assigned value, or the default value for the underlying type if the value is null, for example int j = x.GetValueOrDefault();
  • Use the HasValue and Value read-only properties to test for null and retrieve the value, for example if(x.HasValue) j = x.Value;
  • The HasValue property returns true if the variable contains a value, or false if it is null.
  • The Value property returns a value if one is assigned, otherwise a System.InvalidOperationException is thrown.
  • The default value for a nullable type variable sets HasValue to false. The Value is undefined.
  • Use the ?? operator to assign a default value that will be applied when a nullable type whose current value is null is assigned to a non-nullable type, for example int? x = null; int y = x ?? -1;
  • Nested nullable types are not allowed. The following line will not compile: Nullable> n;




A class defined in two or more files is called a partial class. The keyword partial is used to define the class. When working on large projects, spreading a class over separate files allows multiple programmers to work on it simultaneously. During compile time all the partial class are compiled into one type only.


Listing 1: A Standard Class
public class AIPlayer
{
public AIPlayer()
{
// Construct your class here.
}
public Move GetMove()
{
// Choose the best move and return it.
}


Listing 2: A Class Split Into Two Partial Classes
public partial class AIPlayer
{
public AIPlayer()
{
// Construct your class here.
}
}
public partial class AIPlayer
{
public Move GetMove()
{
// Choose the best move and return it.
}
}

ASP.NET Pages Already Use Partial Classes

First I will remind you again of the ASP.NET pages. Every page you create in ASP.NET is eventually compiled. Every .aspx file will be used to declare a page class. They all inherit from a standard Page class. You can see this in your code behind file. If you view the code of your ASP.NET page you will see a class definition. It will have the partial keyword in the definition and it will look similar to this code.

Listing 3: Codebehind File
public partial class MyWebPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Perform some action here.
}
}


Anonymous methods are a condensed way to declare and use delegates

In C# 1.0 and C# 1.1, we typically assign instances of delegates to event properties. For example, in WinForms a Button control exposes a Click event. The delegate type of Click isEventHandler. EventHandler is a method that takes object and EventArgs arguments. Hence, we can initialize an EventHandler object with any method matching the delegate EventHandler's signature and assign that delegate to Click. Here's how the code might look:

private void Form1_Load(object sender, EventArgs e)
{
button1.Click += new EventHandler(OnClick);
}
private void OnClick(object sender, EventArgs e)
{
Debug.WriteLine("button1 clicked");
}
Because the forms designer for WinForms and the page designer for WebForms automatically add the code for delegate binding, it's possible to write a lot of code without binding delegates manually.

Anonymous Methods Are Inline Delegates

Generally, when we're using delegates, we have a method. That method's signature matches the signature prescribed by a delegate and can be used to initialize a delegate instance. Anonymous methods are used to condense the method and initialization of the delegate into a single location.

Using the example from the previous section, we see how the instantiation of the delegate new EventHandler is distinct from the method OnClick used to initialize the delegate. This code could be compressed into an anonymous method:

private void Form1_Load(object sender, EventArgs e)
{
button1.Click += delegate
{
Debug.WriteLine("button1 clicked");
};
}

To create the anonymous method, notice that we removed OnClick's method header and replaced the construction of the EventHandler delegate with the word delegate followed by OnClick's method body. The resultant behavior is the same. If we want to use the event arguments we would normally find associated with the delegate, we can add an optional parameter list after the worddelegate:

private void Form1_Load(object sender, EventArgs e)
{
button1.Click += delegate(object s, EventArgs ev)
{
Debug.WriteLine("object is " + s.ToString());
};
}
If you define delegate parameters, they must match the parameters defined by the delegate type. For example, Click's type is EventHandler, so if arguments are present they must matchEventHandler's arguments object and EventArgs.

Anonymous methods can be used wherever delegates are expected. Anonymous methods can useref and out arguments, but cannot reference ref or out parameters of an outer scope. Anonymous methods can't use unsafe code, and anonymous methods can't use goto, break, orcontinue in such a way that the branch behavior causes a branch outside of the anonymous method's code block.

Summary
Anonymous methods are examples of methods without names that can be defined and used anywhere a delegate can be used. Delegates are wrappers for event handlers. How practical and generally useful anonymous methods are remains to be seen. I suspect that anonymous methods will be much less useful than overloaded operators and used even less frequently, but anonymous methods are part of .NET and it's useful to recognize them when you see them.
                            
                                                             OR
Anonymous methods can be used anywhere where a delegate type is expected.Anonymous Method declarations consist of the keyword delegate, an optional parameter list and a statement list enclosed in parenthesis.

Code Snippet: Event Handler (without using anonymous methods)
...
btnSave.Click += new EventHandler (btnSave_Click);
...
void AddClick(object sender, EventArgs e)
{
SaveChanges();
lblStatus.Text = "Your changes have been saved";
}

Code Snippet: Event Handler (using anonymous methods)

btnSave.Click += delegate

{
SaveChanges();
lblStatus.Text = "Your changes have been saved";
};

Code Snippet: Event Handler using Anonymous Methods, with a parameter list

btnSave.Click += delegate(object sender, EventArgs e)
{
MessageBox.Show(((Button)sender).Text);
SaveChanges();
MessageBox.Show("Your changes have been saved");
}













The concept of 'Generics', which is included in .NET Framework version 2.0, and which can be considered very close to Templates in C++.
Version 2.0 of the .NET Framework introduces a new namespace viz. System.Collections.Generic, which contains the classes that support this concept, like the List, Queue, Stack, LinkedList and many more which you can use effectively in your programs.


Advantages of Generics



In the earlier versions, before .NET 2.0, generalization was accomplished by casting types to and from the universal base typeSystem.Object. Generics provide a solution to this limitation in the common language runtime and the C# language. This limitation can be demonstrated with the help of the ArrayList collection class from the .NET Framework base class library. ArrayList is a highly convenient collection class that can be used without any modifications to store any reference or value type.

// The .NET Framework 1.1 way of creating a list 

    ArrayList list1 = new ArrayList(); 
list1.Add(3); 
    list1.Add(105); 
    //...

    ArrayList list2 = new ArrayList(); 
list2.Add("First item.");
 
    list2.Add("Second item");
    //...

But this convenience comes at a cost. Any reference or value type that is added to an ArrayList is implicitly typecast toSystem.Object. If the items are value types, they must be boxed when added to the list, and unboxed when they are retrieved. The casting, boxing and unboxing operations degrade performance; the effect of boxing and unboxing can be quite significant in scenarios where you must iterate through large collections.
So, what we need is, flexibility of the ArrayList but it should be more efficient and should provide some ways of type checking by the compiler, without sacrificing on the reusability of that class with different data types. An ArrayList with a type parameter? That is precisely what generics provide. Generics would eliminate the need for all items to be type cast to Object and would also enable the compiler to do some type checking.
In the generic List<T> collection, in System.Collections.Generic namespace, the same operation of adding items to the collection looks like this:

// The .NET Framework 2.0 way of creating a list
" List(int) list1 = new List(int)(); "
  List list1 = new List();
    list1.Add(3); // No boxing, no casting

 
    list1.Add("First item"); // Compile-time error

For the client code, the only added syntax with List<T> compared to ArrayList is the type argument in the declaration and in instantiation. In return for this slightly greater coding complexity, you can create a list that is not only safer than ArrayList, but also significantly faster, especially when the list items are value types.

 There is no need to write code to test for the correct data type, because it is enforced at compile time. The need for type casting and the possibility of run-time errors are reduced.
Also Generics got rid of disadvantage of array list by avoiding the type casting.