Roman
Roman

Reputation: 4513

WCF and various return classed

I've come onto a problem which I can't find a good solution to - I've got a WCF service, where I want to return an object of ChildClass which inherits from FatherClass.

Mostly, I'd return the ChildClass, but in some cases I'd like to return just the FatherClass (which holds just 1 field "error").

Can this be accomplished?

My Code:

[WebGet(UriTemplate = "SomeQueryString", ResponseFormat = System.ServiceModel.Web.WebMessageFormat.Json)]
public ChildClass GetCollection(parameter)
{

    if (err)
    {
        return new FatherClass();
    }
    else
    {
        return new ChildClass();
    }
}

Where as ChildClass inherits from FatherClass (has less fields).

My objective is to return only a very small fraction of the "text" instead of the text that will be returned if I return the whole ChildClass object.

Ideas? :)

Thanks!

Upvotes: 0

Views: 92

Answers (2)

Roland Mai
Roland Mai

Reputation: 31077

I think this is a question about C# and type casting. As you have it, it won't work because ChildClass : FatherClass. See below:

    class FatherClass
    {
        public int x { get; set; }
    }

    class ChildClass : FatherClass
    {
        public int y { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            FatherClass a = new FatherClass();
            ChildClass b = new ChildClass();


            FatherClass c = (FatherClass)b;
            ChildClass d = (ChildClass)a;

            Console.ReadLine();
        }
    }

The cast ChildClass d = (ChildClass)a; will fail. So you could try modifying your signature to

public FatherClass GetCollection(parameter)

and use appropriate type casting.

Upvotes: 0

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364279

That is possible only if you redefine your operation and contracts - you must return parent and serializer must know about all children which can be used instead of the parent:

[KnownType(typeof(ChildClass)]
[DataContract]
public class ParentClass 
{
    // DataMembers
}

[DataContract]
public class ChildClass : ParentClass 
{
    // DataMembers
}

And your operation will look like:

[WebGet(UriTemplate = "SomeQueryString", ResponseFormat = System.ServiceModel.Web.WebMessageFormat.Json)]
public ParentClass GetCollection(parameter)
{
    ...
}

Upvotes: 3

Related Questions