Saturday, March 2, 2013

C# interface-i

Interfejsi su kao ugovor. On definiše metode, property-e, itd. koje svaka klasa mora da implementira ako implementira i taj interfejs. Evo jedan primer iz prakse. Definišeš interfejs za snimanje objekta Student u bazu podataka.
public interface IStudentRepository
{
    Student GetById(int id);
    List GetAll();
    void Save(Student student);
    void Delete(int id);
}
I sada hoćemo da napravimo konkretnu implementaciju tog interfejsa
public class StudentRepositoryEntityFramework : IStudentRepository
{
    public Student GetById(int id)
    {
        // insert some code here
    }

    public List GetAll()
    {
        // insert some code here
    }

    public void Save(Student student)
    {
        if (student.Id > 0)
            Update(student);
        else
            Create(student);
    }

    private void Create(Student student)
    {
        // insert some code here
    }

    private void Update(Student student)
    {
        // insert some code here
    }

    public void Delete(int id)
    {
        // insert some code here
    }
}
Klasa StudentRepositoryEntityFramework je sklopila ugovor sa interfejsom IStudentRepository. To znači da mora da implementira sve metode koje su definisane u interfejsu IStudentRepository i te metode moraju biti public. Save metoda ne može biti private, internal ili protected, ona mora biti public. Tvoja konkretna implementacija može da sadrži i neke metode koje nisu definisane u interfejsu, kao što su Create, Update, itd., ali sve metode koje su definisane u interfejsu moraju biti implementirane i moraju biti public, ok? Interfejsi se najviše koriste kod Dependency injection i Inversion of control pattern-a. Dosta je komplikovano u početku da se skapira, ali poenta je sledeća: Sve što radiš, radiš sa interfejsima, a ne sa konkretnim implementacijama. Zašto? 1. Zbog Unit Testova. Implementaciju možeš uvek da zameniš sa nekim fake objektom. 2. Ako želiš da promeniš implementaciju, tj. nećeš više da koristiš EntityFramework već NHibernate. Ako na 50 mesta u kodu koristiš StudentRepositoryEntityFramework umesto IStudentRepository, onda ćeš na tih 50 mesta morati da zameniš StudentRepositoryEntityFramework sa StudentRepositoryNHibernate. Ako na 50 mesta u kodu koristiš IStudentRepository, onda ćeš izmenu morati da napraviš samo na jednom mestu (na mestu gde se definiše koja klasa se instancira za dati interfejs)! Zasto bi klasa implementirala interfejs da bi se mogla uporediti dva objekta, zasto jednostavno bez interfejsa se ne napravi metod koji ce uporedjivati objekte?

Quick And Easy Custom Events

There are some really great IN DEPTH articles out there on custom events. 
But sometimes we just need down and dirty explanation with some examples. That's what this article is.

Don't be afraid of the idea of creating a custom event. You have probably already worked with events. If you have ever put a button on a form, then double-clicked it to create a method that handles the button.click event, then you have already worked with events.


private void button1_Click(object sender, EventArgs e)
{
    // Here is where you put your code for what to do when the button is clicked.
}
An event handler receives two parameters: The object that sent the event, and an EventArgs. You can define any kind of event arguments you want. Maybe your arguments only need to be a string... maybe your arguments for an event is a picture... maybe you don't need any custom arguments because you only need to be notified with some task is done.

We're going to make:
  • A string event argument
  • An event that uses the string event argument
  • A method that raises the event
  • A method that handles the raised event
In the real would this could work well for logging steps your program is taking, or providing feedback to the user. First the EventArgs, which in this example is just a string:
public class TextArgs : EventArgs
{
    #region Fields
    private string szMessage;
    #endregion Fields

    #region ConstructorsH
    public TextArgs(string TextMessage)
    {
        szMessage = TextMessage;
    }
    #endregion Constructors

    #region Properties
    public string Message
    {
        get { return szMessage; }
        set { szMessage = value; }
    }
    #endregion Properties
}

We have a private field, a public constructor and a public property. That's it: Nothing scary. When you make a new TextArgs you will be providing a string to become the Message to be passed.

Now for the event:

public partial class Form1 : Form
{
 public Form1()
 {
  InitializeComponent();
 }

 #region Events
 public event EventHandler Feedback;
 #endregion Events
      

That's it in line 9: A new event called "Feedback" that uses your new TextArgs. Basically this a way for your Form1 to yell something to any other form (or class) that is listening.

There is no point raising an event if nobody is listening. So we are going to use a method to check first. If there is a subscriber to the event, then we raise the event. If nobody is listening, then we do nothing.

private void RaiseFeedback(string p)
{
 EventHandler handler = Feedback;
 if (handler != null)
 {
  handler(null, new TextArgs(p));
 }
}

That's it! You have created a custom argument, a custom event that uses the argument, and a method to raise the event if someone is listening. To use this in your program yo might do something like this

private void ProcessMyData()
{
   RaiseFeedback("Data process starting...");
   variableOne = variableTwo / variableThree * variableFour;
   string results = variableOne.ToString();
   // Do a bunch of cool charting stuff
   RaiseFeedback("Stage one complete at: " + DateTime.Now.ToString());
   // Do the more complex stuff as part of stage two
   RaiseFeedback("Stage two complete at: " + DateTime.Now.ToString());
}

Notice that while Form1 does it's processing it is not directly trying to force any other work. It is not logging. It is not trying to make Form6 display a MessageBox. It is not trying to force Form3 to display the feedback in a ListBox. It doesn't know or care about anything other than it's own job. This is an important concept. Each class of your program should do one thing, do it well, and do no more. If you need 6 things done then write six methods. Don't try to make one all-encompassing method that does 6 things. It will just make your life tough later when you need to change the sequence of those 6 things, or add things 7, 8, 9 but temporarily stop thing 4. Whatever you do in response to a Feedback event is NOT tightly bound to the process that raises the event and thus the two won't break each other due to minor changes.

Let's subscribe to the Feedback event:

private void Form1_Load(object sender, EventArgs e)
{
   // Do your initial setup of the form once it loads
   Feedback += new EventHandler(Feedback_Received);
}

and create the event handling method:

void Feedback_Received(object sender, TextArgs e)
{
 HistoryListBox.Items.Add(e.Message);
}

Notice the e.Message. That comes from the TextArgs you made earlier. It is the public property Message.

Let's walk through what actually happens when you use this:

// Do some processing;
RaiseFeedback("Igor, it's alive");
// Do some MORE processing;

Code jumps to the RaiseFeedback method where a new TextArgs is created putting "Igor, it's alive" into the Message property.
The event Feedback is raised with the new TextArgs.
Execution then splits. Once the event is raised program flow returns to the next line: // Do some more processing
But, execution also starts in the Feedback_Received event handling method which is going to put the Message of the TextArgs into our HistoryListBox

======= 2 weeks later =======
As your program grows you realize that everything you are sending to the HistoryListBox really should also go to a text file as a log of what your program is doing. You don't have to go through hundreds of places where you called the Feedback. You just create a logging method, and subscribe it to your Feedback event. Boom! Everything to screen now also goes to a text file.

private void Form1_Load(object sender, EventArgs e)
{
   // Do your initial setup of the form once it loads
   Feedback += new EventHandler(Feedback_Received);
   Feedback += new EventHandler(LogFeedback);
}

void LogFeedback(object sender, TextArgs e)
{
 //Write e.Message to my log text file
}

======== Form1 and Form2 =======
Or maybe you need Form2 to react to something that happens in Form1

private void Form1_Load(object sender, EventArgs e)
{
   // Do your initial setup of the form once it loads
   Feedback += new EventHandler(Feedback_Received);
   Feedback += new EventHandler(LogFeedback);

   Form2 myForm2 = new Form2();
   Feedback += new EventHandler(myForm2.FeedbackResponse);
}

public partial class Form2 : Form
{
   public void FeedbackReponse(object sender, TextArgs e)
   {
      //  Handle feedback from some other form
   }
}

Notice that Form2 doesn't have to know where the feedback is coming from. Its is happy in it's ignorance. Some other form subscribed it to it's feedback event. You could have 10 other forms all raise a feedback event and have this Form2 subscribed to all of them. It then becomes a single location to show the entire running operation of your program. 

Original from here

Monday, August 1, 2011

An introduction to Object oriented programming

Introduction:

OOP stands for Object-Oriented Programming. OOP is relatively a new way to program computer applications. Before OOP programmers used to create computer applications using procedural-programming (or structure-programming) but when OOP solved a lot of the problems of the procedural-programming so almost all of the programmers and developers began using OOP languages. In procedural- programming all the program functionality written in a few modules of code or maybe one module (depending on the program)and these modules depend on one another and maybe if you change a line of code you will have to rewrite the whole module again and maybe the whole program, but in Object-Oriented Programming programmers write independent parts of a program called classes each class represent a part of the program functionality and these classes can be assembled to form a program and when you need to change some of the program functionality all what you have to do is to replace the target class which may contain a problem. So in OOP applications create by the use of classes and these applications can contain any number of classes. That will get us to discuss the Class and Object concept.

Classes and objects:

You may find it not easy to understand the class and object story but I will try to do my best explaining it. Actually the class and object concept is related to each other and some beginners don’t care about understanding it clear so I think they will have a hard times learning C#.

Object-Oriented concept takes the most of its functionality from the real-life concepts. For example, I will discuss the concept of Classes and Objects of the world first and then you will understand the computers Classes and Objects before I even write anything about it.

Worlds Classes and Objects:

In our world we have a classes and objects for those classes. Everything in our world considered to be an object. For example,people are objects, animals are objects too, minerals are objects, everything in the world are objects. Easy right, but what about classes. In our world we have to differentiate between objects that we are living with. So we must understand that there are a classifications (this is how they get the name and the concepts of the Class) for all of those objects. For example, I’m an object, David is object too, Maria is another object so we are from a people class (or type).

I have a dog called Ricky so it’s an object, My friend’s dog called Doby is also an object so they are from a Dogs class (or type). A third example, I have a computer Pentium III this is object, My friend have a computer Pentium IV so this is another object and they are from a Computers class (or type). Now I think you got the concept of the Class and Object but let me crystallize it for you. In our world we have a classifications for objects and every object must be from some classification.

So a Class is a way for describing some properties and functionalities or behaviors of a group of objects. In other words, the class considered to be a template for some objects. So maybe I will create a class called person so this is a template of the functionality and the properties of persons. I explained it by more than a way so wait until you see the first example and I think you will grasp it completely.

Computers Classes and Objects:

Computers Classes discussion is similar to what you grasp from the last section with some modifications to become computerized.
A C# Class Considered being the primary building block of the language. What I mean by the primary building block of the language is that every time you work with C# you will create Classes to form a program. We use Classes as a template to put the properties and functionalities or behaviors in one building block for some group of objects and after that we use that template to create the objects we need.

For example, We need to have persons objects in our program so the first thing to do here is to create a Class called Person that contains all the functionalities or behaviors and properties of any person and after that we will use that Class or template to create as many objects as we need. Creating object of a specific class type called”instance of the class”. Don’t worry if you didn’t grasp it 100% and don’t worry if you don’t know what’s the Class and Object’s properties and functionalities or behaviors because we still in the beginning and until now I didn’t give any code examples. So let’s take a brief of what’s the Class and what’s an object.

The Class : Is a building block that contains the properties and functionalities that
describe some group of objects, We can create a class Person that contains:

1- The properties of any normal person on the earth like :Hair Color, Age, Height, Weight, Eyes Color.

2- The functionalities or behaviors of any normal person on the earth like : Drink water, Eat, Go to the work and later we will see how we can implement the functionalities or behaviors and properties.

There are 2 kinds of classes : The built-it classes that come with the .NET Framework and called Framework Class Library. And the programmer defined-classes which we create it.

The class contains data (in the form of variables and properties) and behaviors (in the form of methods to process these data). We will understand this concept more later in the article.

When we declare a variable in a class we call it member variables or instance variables. The name instance come from the fact that when we create an object we instance a class to create that object so instance of a class means object of that class and instance variable means variable that exists in that class.

The Object : It’s object of some classification (or class, or type. All means the same thing) and when you create the object you can specify the properties of that object. What I mean here is me as an object can have a different properties (Hair Color, Age,Height, Weight) of you as another object. For example, I have a brown eyes and you have a green eyes so when I create 2 objects I will specify a brown color for my object’s Eyes Color property and I will specify a green color for your object’s Eyes Color property.

So to complete my introduction to Classes we must discuss Properties and Variables.

Properties and Variables:

Variables declared in a class store the data for each instance, What that means ? means that when you instantiate this class (that is, When you create an object of this class) the object will allocate a memory locations to store the data of its variables. Let’s take an example to understand it well.


class Person
{
  public int Age;
  public string HairColor;
}

This is our simple class which contains 2 variables. Don’t worry about public keyword now because we will talk about it later . Now we will instantiate this class (that is, When you create an object of this class).


static void Main(string[]args)
{
  Person Michael = newPerson();
  Person Mary = new Person();

// Specify some values for the instance variables
  Michael.Age = 20;
  Michael.HairColor = “Brown”;
  Mary.Age = 25;
  Mary.HairColor = “Black”;
// print the console’s screen someof the variable’s values
  Console.WriteLine(“Michael’s age = {0}, and Mary’s age= {1}”,Michael.Age,
  Mary.Age);
  Console.ReadLine();
}

So we begin our Main method by creating 2 objects of Persontype. After creating the 2 objects we initialize the instance variables for object Michael and then for object Mary. Finally we print some values to the console. Here when you create Michael object C# compiler allocate a memory location for the 2 instance variables to put the values there. Also the same thing with Mary object the compiler will create 2 variables in the memory for Mary object.
So each object now contains a different data. Note that we directly accessed the variables and we may put any values we want. Right, so maybe someone like me will put in my object’s variable Age value of 120 years so I will not get any kind of jobs. But wait there are a solution for this problem. We will use properties.

Properties:

Properties is a way to access the variables of the class in a secure manner. Let’s see the same example using properties.

class Person
{
 private int age;
 private string hairColor;
 public int Age
 {
 get
 {
   return age;
 }
 set
 {
  if(value <= 65 && value >= 18)
  {
    age = value;
  }
  else
    age = 18;
 }
}

public string HairColor
 {
   get
  {
    return hairColor;
  }
  set
  {
   hairColor = value;
  }
 }
}

I made some modifications but please just take care about the 2 new properties that I created it here. So the property now consists of 2 accessors. The get accessor which is responsible for retrieving the variable value, and the set accessor which is responsible for modifying the variables value. The get accessor code is very simple we just use the keyword return within the variable name to return its value, so the following code

get
{
 return hairColor;
}

return the value stored in hairColor.

Let’s put this code at work and after that discuss the set accessor.

static void Main(string[]args)
{
 Person Michael = new Person();
 Person Mary = new Person();

// Specify some values for the instance variables
  Michael.Age = 20;
  Michael.HairColor = “Brown”;
  Mary.Age = 25;
  Mary.HairColor = “Black”;

// print the console’s screen some of the variable’s values
  Console.WriteLine(“Michael’s age = {0}, and Mary’s age= {1}”,Michael.Age, Mary.Age);
  Console.ReadLine();
}
Here I created the same objects from last example the modifications that I used only properties to access the variable instead ofaccess it directly. Look at the following line of code.

Michael.Age = 20;
When you assign a value to the property like that C# will use the set accessor. The great thing with the set accessor is that we can control the assigned value and test it and maybe change to in some cases. When you assign a value to a property C# change the value in a variable and you can access the variable’s value using the reserved keyword value exactly as I did in the example. Let’s see it again here.

set
{
  if(value <= 65 && value >= 18)
  {
 age = value;
  }
  else
    age = 18;
}

Here in the code I used if statement to test the assigned value because for some reason. I want any object of type Person to be in age between 18 and 65. Here I test the value and if it in the range then simply I will store it in the variable age and it it’s not in the range I will put 18 as a value to age. It was just a simple example for the properties.

How we create objects and classes ?

We create classes by define it like that:

using the keyword class followed by the class name like that

class Person
then we open a left brace “{” and after we write our methods and properties we close it by a right brace “}”. That's how we create a class. Let’s see how we create an instance of that class.

In the same way as we declare a variable of type int we create an object variable of Person type with some modifications:

int age;
Person Michael = new Person();
In the first line of code we specified integer variable called age. In the second line we specified first the type of Object we need to create followed by the object’s name followed by a reserved operator called new and we end by typing the class name again followed by parenthesis “()”.

Let’s understand it step-by-step. Specifying the class name at the beginning tell the C# Compiler to allocate a memory location for that type (C# compiler knows all the variables and properties and methods of the class so it will allocate the right amount of memory). Then we followed the class name by out object variable name that we want it. The rest of the code”=new Person();” call the object’s constructor. We will talk about constructor later but for now understand that the constructor is a way to initialize your object’s variable while you are creating it not after you create it. For example, The Michael object we created it in the last section can be written as following :

Person Michael = new Person(20, “Brown”);

here I specified the variable’s values in the parameter list so I initialized the variables while I’m creating the object. But for this code to work we will need to specify the constructor in the Person class and I will not do that here because constructor section will come in later articles.

Wednesday, July 6, 2011

What is Serialization in .NET, types of Serialization and why we need it while developing an application?

Serialization is the process of saving the state of an object by converting it to a stream of bytes. The object can then be persisted to file, database, or even memory. The reverse process of serialization is known as deserialization . In this article, I discuss the uses of serialization and various techniques that can be used to perform serialization. I also take a look at how serialization works and how I can selectively prevent certain members of an object from being serialized.
Serialization
Uses for serialization
Serialization is used in many scenarios, but the main purpose is to save the state of an object in order to have the ability to recreate the same object when required. It is an important to let the user save work and then be able to continue from that point at a later time. This is a common need in various tools and applications. Serialization is also used in creating a clone of an object.

Another important need for serialization arises when the object is required to travel electronically over wire. In such cases the objects are serialized and deserialized. In fact, serialization is one of the fundamental requirements for techniques such as .NET Remoting.

Even the hibernation mode in the Windows Operating system can be considered a form of serialization.

Types of serialization
The .NET Framework provides certain built-in mechanisms which can be used to serialize and deserialize objects. This functionality can be found in the System.Runtime.Serialization and the System.Xml.Serialization namespaces of the .NET Framework.

Serialization in .NET can be classified into four types as shown in


Four types

This classification arises from the format in which the data in the object is persisted. Each of the serialization techniques mentioned have different capabilities and each excel in specific scenarios. The XML serialization technique can convert only the public properties and fields of an object into an XML format. The XML serialization is also known as shallow serialization.

This inability of the XMLSerializer to serialize the private fields of an object is overcome by the SOAP and binary serialization techniques. In the binary and SOAP serialization techniques, the state of the entire object is serialized into a stream of bytes. In cases where the object contains a reference to other objects, even those are serialized. This type of serialization is known as deep serialization.

In addition to these techniques, the .NET Framework also provides the developer control over the serialization process. This can be achieved by implementing the ISerializable interface, which will be discussed separately under custom serialization in the next part of this article.



The SOAP and binary serialization functionality is provided by means of various Formatters in the .NET Framework. Aligned with the classifications of XML serialization and binary serialization, the .NET Framework also provides the SoapFormatter and the BinaryFormatter classes. These classes implement the IRemotingFormatter and the IFormatter interfaces.

The main methods which encapsulate the functionality of serialization are the Serialize and Deserialize methods. The SoapFormatter and the BinaryFormatter are the concrete classes which enable the serialization process within the .NET Framework.

Let us now take a look at some code. The code in Listing A shows a sample class being serialized and deserialized in C#.

An instance of the SoapFormatter object is created and the Serialize method is called and a FileStream is passed to enable serialization. The technique for using a binary formatter would be the same except that instead of the SoapFormatter, an instance of the BinaryFormatter would need to be created.

Comparison: Which technique to use?
The XmlSerializer can be used when you need the data in the object to be stored in an XML Format. However, this serialize has the limitation that it can serialize only the public fields of an object.

The SoapFormatter is ideal in scenarios where you need interoperability. This is ideal in applications spanning heterogeneous environments.

The BinaryFormatter generates a very compact stream when an object is serialized as compared to the other two techniques and hence is useful when data needs to travel electronically across the wire. This is appropriate when the applications do not involve heterogeneous environments.

Serializable attribute
The developer would need to mark a class as serializable using the appropriate attribute in order for the object of that class to indeed be serializable. In fact, the serialization feature is a design time issue because an object cannot be made serializable at runtime.

The code snippet below shows the usage of SerializableAttribute:
[Serializable]
public class MyClass

The SerializableAttribute needs to be applied even when the class implements the ISerializable interface. When an attempt is made to serialize an object which is not marked as Serializable, the CLR throws a SerializationException.

The SerializableAttribute comes in handy whenever the object needs to cross application domains or travel over the wire. The developer does not need to write any plumbing code for the serialization process to work. Once a class is marked as serializable, if the need arises for serialization, the .NET Framework will employ reflection and automatically serialize and deserialize objects which cross application domains or participate in .NET Remoting.

Selective serialization
In certain scenarios, it may be beneficial to serialize an object in parts. Certain objects might contain information which is sensitive and for security reasons such information should not be serialized. Also, it might not make sense to serialize certain data like the reference to another object or storing a Thread ID. This data might not be valid when the object is deserialized.

For such situations, the .NET Framework provides the NonSerialized attribute. This attribute can be used to prevent particular member variables of an object from being serialized.

The sample code in Listing B demonstrates this attribute.

In the sample code listing, if the SampleObject class were to be serialized, then the data in string variable strSecret would not.

This attribute however, does not apply to the XMLSerializer. The same results could be obtained using the XMLSerializer by making use of the XmlIgnoreAttribute class.

The code sample in Listing C shows how the same results could be obtained using XMLSerializer.

Serialization
In this introductory article to serialization I looked at what serialization is and where it is used. The article also dealt with selective serialization where only parts of an object are to be serialized. The final part of this article deals with more advanced topics associated with serialization such as implementing ISerializable and ICloneable.


Here are the following steps that we are going to do to create a serializable class and test it.

Create a custom class named Employee and assign properties.
Define the serialization functions.
Create a main class and instantiate our Employee class.
Serialize the object to a sample file.
Deserialize the values by reading it from the file.

Defining Employee class and properties
Our custom class Employee should be derived from the ISerializable interface and should hold the Serializable attribute. Here is the code snippet.

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary; namespace MyObjSerial
{
[Serializable()] //Set this attribute to all the classes that want to serialize
public class Employee : ISerializable //derive your class from ISerializable
{
public int EmpId;
public string EmpName;

//Default constructor
public Employee()
{
EmpId = 0;
EmpName = null;
}
}
}

Thursday, April 7, 2011

Type-safety .NET

Type safety means that the compiler will validate types while compiling, and throw an error if you try to assign the wrong type to a variable.

Some simple examples:

// Fails, Trying to put an integer in a string
  
String one = 1;

// Also fails.
  
int foo = "bar";

This also applies to method arguments, since you are passing explicit types to them:
  
int AddTwoNumbers(int a, int b)
{
return a + b;
}


If I tried to call that using:
  
int Sum = AddTwoNumbers(5, "5");

The compiler would throw an error, because I am passing a string ("5"), and it is expecting an integer.

In a loosely typed language, such as javascript, I can do the following:
  
function AddTwoNumbers(a, b)
{
return a + b;
}

if I call it like this:
  
Sum = AddTwoNumbers(5, "5");

Javascript automaticly converts the 5 to a string, and returns "55". This is due to javascript using the + sign for string concatenation. To make it type-aware, you would need to do something like:
  
function AddTwoNumbers(a, b)
{
return Number(a) + Number(b);
}

Or, possibly:
  
function AddOnlyTwoNumbers(a, b)
{
if (isNaN(a) || isNaN(b))
return false;
return Number(a) + Number(b);
}

if I call it like this:
  
Sum = AddTwoNumbers(5, " dogs");

Javascript automatically converts the 5 to a string, and appends them, to return "5 dogs".

Not all dynamic languages are as forgiving as javascript (In fact a dynamic language does not implicity imply a loose typed language (see Python)), some of them will actually give you a runtime error on invalid type casting.

While its convenient, it opens you up to a lot of errors that can be easily missed, and only identified by testing the running program. Personally, I prefer to have my compiler tell me if I made that mistake.

Now, back to C#...

C# supports a language feature called [covariance](http://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)#C.23), this basically means that you can substitute a base type for a child type and not cause an error, for example:
  
public class Foo : Bar
{
}


Here, I created a new class (Foo) that subclasses Bar. I can now create a method:
  
void DoSomething(Bar myBar)

And call it using either a Foo, or a Bar as an argument, both will work without causing an error. This works because C# knows that any child class of Bar will implement the interface of Bar.

However, you cannot do the inverse:
  
void DoSomething(Foo myFoo)

In this situation, I cannot pass Bar to this method, because the compiler does not know that Bar implements Foo's interface. This is because a child class can (and usually will) be much different than the parent class.