Tuesday, August 23, 2011

How to return derived class from WCF when the signature is defined for base

Hi friends,
First.. sorry for not posting any new info for so long.

The concept of late binding, where one can use the object of derived class, instead of the base class. (this works because the object of base class can hold the object of the derived class and it is one of the basic principles of OOPS)

But, if you try to use this feature of OOPS directly in WCF, you will get an error, and because of that error, many .NET programmers feel that this feature is not supported in WCF. (They should know that it is a basic principle, and it must be supported)

In order to make this work in WCF, there is a small thing to do:
We will take this example for better understanding:
We have a base class, and we will name it "Base"
We also have 2 derived classes viz. Derived1 and Derived2

[DataContract]
public class Derived1 : Base
{
...
}

[DataContract]

public class Derived2 : Base
{
...
}

And we have a method defined in the interface as:
Base GetData();

Based on some condition, this method should return either object of type Derived1 or Derived2. For this to work, we will add following 2 lines on top of the Base class definition:


[KnownType(typeof(Derived1))]
[KnownType(typeof(Derived2))]

Now try and test.
:)
Good day

No comments: