I've got an object of type Derived but want to have one of type Base. Normally, I can simply cast the object to a reference of Base. However, for my WCF service, I really want to expose the Base class only.
Is there a neat way to get the Base to a Derived object (or create a new Base from the Derived object) where the dynamic type is Base?
Example:
myWcfResult.PropertyOfTypeBase = objectOfTypeDerived; // do some magic in this line
Assert.Trace(myWcfResult.PropertyOfTypeBase.GetType() == typeof(Base)); // should hold afterwards
// or at least WCF should be able to serialize it correctly into an XML element of type Base
If what you are trying to achieve is to hide the extra properties of the Derived class, then there are two options
Either the consumer allows you to specify the type explicitly
Or you have to change your design.
In the second case you should consider using composition instead of inheritance e.g.
Wrap the Base or Derived objects into a new adapter class that will only expose the required properties
Have the Base class as it is, but instead of adding the extra functionality by deriving from it, use composition: the Base class would contain another object that would define some aspects of the behaviour.
It is difficult to help you without a concrete example I am afraid.
If nothing else comes up I'm going to accept my own hackaround as solution: using AutoMapper to clone the Derived into a new Base:
Mapper.CreateMap<Base,Base>();
Mapper.Map<Base,Base>(objectOfTypeDerived);
Related
I don't get the connection of Interfaces To polymorphism.
Polymorphism for me is about executing a method in a different way for some different concrete classes using abstract methods or virtual methods+ overriding and therefore this is only linked to inheritance in my vision, but how do you override methods With Interfaces??
How do you use Interfaces for doing same method in different ways and giving the object to decide what to do according to its concrete type?
Thanks
As stated by Andreas Hartl in his article on Inheritance Vs. Interfaces:
Many high-level languages support inheritance and interfaces, and for
someone new to the concepts, it's sometimes not clear which one to
choose. Although languages differ in their exact handling of
inheritance and interfaces, the basics are usually the same, so this
tip should be valid for most languages.
Inheritance means that we derive one class (the derived class) from
another class (the base class). The derived class is an extension of
the base class. It contains all the features (methods and data
members) of the base class, can extend it with new features, and can
reimplement virtual methods of the base class. Some languages, like
C++, support multiple inheritance, where a derived class can have
multiple base classes, but usually inheritance is restricted to a
single base class.
Interfaces can usually only define methods and no data members (but C#
for example allows data members in the form of properties within
interfaces), and a class can always implement multiple interfaces. An
interface contains only method definitions without implementations,
and a class that implements an interface supplies the implementation.
So, using inheritance, you write a base class with method
implementations, and when you derive a class from it, this class will
inherit everything from the base class, and is immediately able to use
its features. An interface on the other hand is just a contract of
method signatures, and a class that wants to implement an interface is
forced to supply the implementations for all methods of the interface.
So when do you use which? In some cases, the language already dictates
what you use: if you need your class to have multiple 'parents', you
cannot use inheritance in languages that don't support multiple
inheritance. And if you want to reuse a library object, you have to
use the fitting concept, depending on if that library object is a
class or an interface.
But which to use if you are free to choose? Basically, base classes
describe and implement common behavior of related types, while
interfaces describe functionality that unrelated types can implement.
Inheritance describes 'is a' relationships, interfaces describe
'behaves like' relationships. For example, say that you are writing a
flight simulator. Your basic entity, which you will for example store
in a list, will be 'Airplane'. Your concrete types will be 'Concorde'
and 'Phantom'. So how should you model the three types? Concorde and
Phantom are related, they both are airplanes and share data, like
'Weight' or 'MaxSpeed' and functionality, like 'Accelerate', so we can
model them with inheritance. 'Airplane' will be the base class with
common data and methods, and 'Concorde' and 'Phantom' will derive from
'Airplane'. We could say that both are specialized airplanes, which is
why it's often said that inheritance means specialization. Now assume
that we also add a class 'Pilot' to our program, and we want to give
the user the ability to save the game and load it later. So when he
saves the game, we need to save the state of all Aircrafts and the
state of all Pilots. And we want to do this in one function that takes
just a list of all saveable objects. So how do we model this? To
answer this, we must take a look at the different types we want to
save. Pilots and Airplanes. It's obvious that they are not related at
all. They share no common data and no common functionality. We can see
that writing a base class 'Saveable' and derive both Pilot and
Airplane from it would make little sense, since no code in Saveable
could be reused by Airplane or Pilot, since both have no common
properties. In this case, an interface is the best solution. We can
write an interface 'ISaveable' with a method Save(). Pilot could then
implement ISaveable.Save() by saving his name, while Airplane could
save its current speed and coordinates.
As you can see, a clear image of the relationship between classes
often makes the choice clear: Use inheritance for related types, where
each derived class 'is a' base class. Use interfaces for unrelated
types which have some common functionality.
Here are some more points to consider with inheritance and interfaces:
Interfaces are fixed. When you change an interface, you have to change every class implementing that interface. But when you change a
base class, every derived class will gain the new functionality, which
can both be good (if you make a bugfix in some base class method
implementation, a derived class using that method will gain the bugfix
without you needing to change it) or bad (if a change in the baseclass
introduces a new bug, all derived classes using the method will be
bugged too).
Interfaces are usually more flexible, since in most languages you can only derive from one class, but implement many interfaces
Interfaces help to protect internal classes: Assume class A has an internal object b of class B. When a method in A returns a pointer or
reference to b, the code that called this method now has access to the
whole object b, which can be dangerous if A only wants to expose
certain members of b. This problem can be solved if you create an
interface I with just the members which are safe to expose. When B
implements this interface, and your method in A returns b via an I
pointer or reference, the outside code can only do what you allow
through the interface.
Polymorphism as a concept does not require inheritance, although in many languages inheritance is the only way to achieve it. Some languages, like smalltalk allow you to polymorphically use any type that implements the same set of members and properties. If it looks like a duck, quacks like a duck, and walks like a duck, you can treat it like a duck.
Polymorphism is simply the ability to treat one object as another object, by providing the same way to access and use it as the original object. This is best illustrated by the Liskov Substitution Principle. This is called the "Interface" or sometimes "Contract", because it defines a "signature" that another object can use to do interesting things to the object.
in C#, you can inherit from interfaces or other (non-sealed) classes. The difference is that an interface does not provide any actual storage or methods (only their "signature"), it is merely a definition. You can't instantiate an interface, you can only instantiate an object that implements an interface.
Classes implement an interface (IDisposable, for instance) in the same way you build a house based on blue prints. If you build two houses with the same blueprints, then each house has the exact same "interface", they may have different color paint, or carpeting, but they function in exactly the same way, yet they are two distinctly different houses, with many differences in how various things might function.
When it comes to C#, just know that an interface says what properties or members an object that implements it MUST have. Likewise, in C#, a big difference is that you can inherit multiple interfaces but only ever a single class. (ie public class Test : BaseClass, IDisposable, ITest, IFooBar)
consider this...
public int SomeMethod(SomeBaseClass object)
{
// Pass in a descendant classe that implements / overrides some method in SomebaseClass
}
public int SomeMethod(ISomeInterface intf)
{
// pass in concrete classes that implement some ISomeInterface function
}
This is the basic essence of polymorphic behavior, a common contract, implemented specifically by a specialist class.
Maybe the title is not so clear. Let me clarify what I'm trying to accomplish.
I have to base classes:
BaseProperties
BaseProblem
BaseProperties contains data about the generation of math problems. For example, in the image above, BasicAdditionProperties contains Addend1 and Addend2, this two objects know about the range of the generated value to represent a BasicAdditionProblem.
So, this is just an idea.. I guess I supposed to pass the abstract class to a factory, and this one should generate the problem (in this case BasicAdditionProblem).
I have read, it's recomended pass these values as the base class. And my main doubt is, when I pass the object BaseProperties to the factory, all the time do I have to cast the object?
Or what ideas can I implement to model this scenario? Or do I have to have a static Factory where maintain and be used as mapping to the concrete factories?
Thanks in advance.
Define an abstract CreateProblem() in the BaseProperties class. This method can be used generically to allow each concrete Properties subclass to provide its own Factory method.
This is similar to using an instance of WebRequest subclass and calling GetResponse() on it and it then returns the coresponding subclass of WebResponse.
This distributed abstract factory approach allows you to add property/problem pairs easily to the system because the code to map the two is solely contained in those two classes.
You could also use a full Abstract Factory implementation where you have PropertyProblemFactory that defines a CreateProperties() and a CreateProblem(). So in your example you would have AdditionFactory that knows how to create the matching set. But this forces you to define an additional class for each Property/Problem pair. It also works best when you have a class that uses the current/selected PropertyProblemFactory, creates a Properties with it, and then immediately uses that same PropertyProblemFactory factory to create the matching Problem. Once you let go of the reference to the factory and solely have just a reference to the Properties, it is harder to re-locate the right factory to create the Problem. (This can be addressed with yet another class to map object types to factories, but the complexity rises. So the first appoach I suggested is better in this kind of situation).
There are multiple solutions for this. It just depends on how you want to program it.
abstract methods in the abstract class must be handled in all classes that inherit from the abstract class. This way you can easily call abstract methods in the factory without casting.
However when you need to use lots of data from just one specific class then it would not be wise to make abstract methods for it and you should just simply cast the object.
So it all depends on how much classes inherit from BaseProperties and how much data in those classes are the same.
Difference between accessing an object’s methods with an object reference vs an interface reference, even if both refer (point) to the same object.
I dont know what is object
referene and interface reference please explain?
If you have a reference to an object using an interface, you will only have access to that objects methods or properties that are defined in the interface. If you need to access any additional methods, you have to identify the specific type of the implementation, and cast it to that type before calling those methods or properties.
Using the interface type instead of the actual type is often done to reduce coupling between objects. For example, one of your objects that are logging something might need an instance of ILogger, but it should not really care if the implementation of ILogger logs to a file, to a web-service or does something else. It should only care about getting an object that fullfills the contract that the interface defines.
If I understand you question correctly you are asking the difference between object of a class and object of an interface
Object of a class contains full implementation of the class. You will be able to call all the public methods and use public fields of that class through the class object.
On the other hand, interface object only exposes those methods and fields which are defined by interface.
One case is when you know the type of your object (so the class your object is an instance of) and this way you can access all its methods. Let me stress that again: you know the class of the object.
Second case is when you only know that your object implements an interface, you do not know which class your object is. This way you only have access to the methods that the class inherits from that particular interface, and no other method.
It's actually very simple. When you access object methods, with interface reference you can only access the methods that are part of that interface definition which are implemented by that object's class.
And when you access them with class reference then you can access all that are part of the class.
Actually with interface you don't care what is the actual class of that object, you only want to be concerned with the interface methods, that are implemented in that class, so you can access only those..
Take for instance the SqlBulkCopy.WriteToServer() method. One of the overloads takes an IDataReader as the parameter. My question is, what's the benefit/advantage to passing an interface to a method instead of the object instance itself?
http://msdn.microsoft.com/en-us/library/434atets.aspx
You can have many possible implementations for that one interface. Its better to depend on an abstraction (in this case an interface) than an actual concrete class - this allows much better flexibility and testability.
This also puts the focus on what is really required by the WriteToServer() method - the only thing its contract requires is for the caller to pass in any instance of a concrete class that provides the methods / properties declared by the IDataReader interface.
Passing an interface means that you can pass any object that implements that interface not just one particular object.
This makes the code more flexible as it doesn't have to know about all the possible objects that may implement the interface now or in the future.
It also makes it more robust as it only has to deal with the properties and methods on the interface which are well known and defined.
The formal parameter type is an interface type - that means that you can pass in any object that implements this interface (or rather, an instance of an object that implements the interface).
You are not passing in an interface, you are passing in an object that conforms to the contract defined by the interface.
So, if your data source is SQL Server, you would pass a SqlDataReader, if Oracle, an OracleDataReader.
You could also implement your own data reader and pass that to the function and even write a mock data reader to test the method thoroughly.
This is a well known design principle - Program to an Interface, not an implementation.
And from MSDN - When to Use Interfaces:
Interfaces are a powerful programming tool because they let you separate the definition of objects from their implementation.
When a method lists one of its arguments as an interface, it isn't requesting you to pass in an instance of that interface (which is impossible anyway, you can create instances of interfaces), it's asking you to pass in any object that implements that interface.
Example:
interface IMyObject {
public void SomeMethod();
}
public class MyObject : IMyObject {
public void SomeMethod() {
// implementing code here
}
}
You can now pass any instance of MyObject as an argument that is of type IMyObject :)
public class YourObject {
public void DoSomething(IMyObject o) {
// some code here
}
}
YourObject yo = new YourObject();
MyObject mo = new MyObject();
yo.DoSomething(mo); // works
I hope that makes sense!
Actually, it expects you to pass an instance of a type that implements the interface, rather than the interface itself.
The interface type is used when the only thing the method cares about are the methods declared by the interface. As long as the object implements that interface, methods defined in it can be invoked on the object.
This is one of the reasons for interfaces - in this example, all the consumer of the interface (i.e. the function) cares about is that it can read data - it doesn't mind whether it's from an SqlDataReader or an OleDataReader or for any other provider - the alternate would be providing separate overloads that are virtually identical for every possible Data Reader (which is of course impractical, given someone may come up with one for, say dBase or a more exotic database engine)
Ok so I'm currently working with a set of classes that I don't have control over in some pretty generic functions using these objects. Instead of writing literally tens of functions that essentially do the same thing for each class I decided to use a generic function instead.
Now the classes I'm dealing with are a little weird in that the derived classes share many of the same properties but the base class that they are derived from doesn't. One such property example is .Parent which exists on a huge number of derived classes but not on the base class and it is this property that I need to use.
For ease of understanding I've created a small example as follows:
class StandardBaseClass {} // These are simulating the SMO objects
class StandardDerivedClass : StandardBaseClass {
public object Parent { get; set; }
}
static class Extensions
{
public static object GetParent(this StandardDerivedClass sdc) {
return sdc.Parent;
}
public static object GetParent(this StandardBaseClass sbc)
{
throw new NotImplementedException("StandardBaseClass does not contain a property Parent");
}
// This is the Generic function I'm trying to write and need the Parent property.
public static void DoSomething<T>(T foo) where T : StandardBaseClass
{
object Parent = ((T)foo).GetParent();
}
}
In the above example calling DoSomething() will throw the NotImplemented Exception in the base class's implementation of GetParent(), even though I'm forcing the cast to T which is a StandardDerivedClass.
This is contrary to other casting behaviour where by downcasting will force the use of the base class's implementation.
I see this behaviour as a bug. Has anyone else out there encountered this?
I see this behaviour as a bug.
This behavior is correct. Since your method DoSomething is constraining T to StandardBaseClass, you only have access to the specific methods of StandardBaseClass, not any methods or properties of a derived class. Since StandardBaseClass does not have a Parent property, this is invalid, and should be invalid, by design.
There are two potential options here - You can use reflection to pull out the Parent property, or use C# 4's dynamic type, and treat this as a dynamic object. Both bypass the standard type checking in the compiler, however, so will require you to do extra type checking at runtime to verify that the Parent property exists.
Create an interface that contains the Parent property. Have each class that has a Parent property implement that interace. You will then be able to create a generic method that accepts a parameter of type IHaveParent, and it will do the right thing.
For anyone that is interested an succinct answer to this situation is answered by Stephen Cleary on msdn here:
http://social.msdn.microsoft.com/Forums/en-AU/csharpgeneral/thread/95833bb3-fbe1-4ec9-8b04-3e05165e20f8?prof=required
To me this is a divergence in the class hierarchy. By this this I mean that either the base class has parent, or the derived classes with Parent are derived from an abstract child of the base.
Lol as John says, an interface as opposed to an abstract class is sufficient too.
You idea won't work because the compiler can never guarantee that the base class actually would have such a property. And it won't just select the "right" one based on if it has it or not.
The only way you can do this is using reflection and then test at runtime if the requested property exists on the inspected class. You have to judge yourself if that is a viable way to do for your project (reflection is slow and requires maximum rights).
This is correct, as the compiler only knows that it can bind to your type as a StandardBaseClass. The binding is not done at runtime (where it could potentially decide to use the StandardDerivedClass overload.
If you know that it's a StandardDerivedClass, then why not just cast it as such?
object Parent = ((StandardDerivedClass)foo).Parent;
It's a bit ugly, but you can accomplish this using a Registration system, where you register delegates for different possible derived classes that expose the 'shared' property/method and then use something like a Dictionary<Type,Func<SomeT>> to store the delegates. If you know all of the derived types ahead of time and don't have to load plug-ins or the like, you can also use the classic ugly if/else-if structure. Either way you're basically creating your own substitute for what should have been supported by the virtual method table.