Referencing a Class Through Its Interface Visual C Sharp 2010

In the same way that you can reference an object by using a variable defined as a class that is higher up the hierarchy, you can reference an object by using a variable defined as an interface that its class implements . Taking the preceding example, you can reference a Horse object by using an ILandBound variable, as follows:

Horse myHorse = new Horse(...); 
ILandBound iMyHorse = myHorse; // legal

This works because all horses are land-bound mammals, although the converse is not true, and you cannot assign an ILandBound object to a Horse variable without casting it first to verify that it does actually reference a Horse object and not some other class that also   happens to implement the ILandBound interface .
The technique of referencing an object through an interface is useful because it enables you to define methods that can take different types as parameters, as long as the types implement a specified interface . For example, the FindLandSpeed method shown here can take any argument that implements the ILandBound interface:


int FindLandSpeed(ILandBound landBoundMammal) 

    ... 
}

Note that when referencing an object through an interface, you can invoke only methods that are visible through the interface .

No comments:

Post a Comment