tags:

views:

32

answers:

2

Am I correct in thinking that if I have a WCF OperationContract takes in an object and needs to set a property on that object so the client gets the update, I need to declare it to return the object.

e.g. given a datacontract:

[DataContract]
public class CompositeType
{
    [DataMember]
    public int Key { get; set; }

    [DataMember]
    public string Something { get; set; }
}

this will not work with WCF:

public void GetDataUsingDataContract(CompositeType composite)
{
  composite.Key = 42;              
}

this will work:

public CompositeType GetDataUsingDataContract(CompositeType composite)
{
  composite.Key = 42;

  return new CompositeType
  {
    Key = composite.Key,
    Something = composite.Something
  };           
}
+1  A: 

If you use 'out of the box' WCF, you are actually using a form of webservices, that uses serialized versions of the objects that are sent from client to server. This is the reason you cannot 'by reference' change properties on objects. You will always have to use a request / response pattern.

Robert
+1  A: 

IMO, authoring methods that produce output via side-effects is a "bad" thing. Having said that however, are there circumstances that necessitate this model? Yes.

Certainly C# programming model permits this, is WCF broken? No. At a certain point, one must realise they are consuming WCF, and as a framework it attempts to satisfy a majority of use-cases [for instance, replicating all input parameters on all round trips to preserve implicit side effect semantics is, in a word, silly].

Of course, there are ways to work around this - C# also provides for explicit declaration of these scenarios and WCF supports these as well!

For instance

// use of "ref" indicates argument should be returned to 
// caller, black-eye and all!
public void GetDataUsingDataContract (ref CompositeType composite) 
{
    composite.Key = 42;         
}

Give it a go!

Hope this helps :)

johnny g
Interesting. I had no idea that this was possible. I take it that this is not exactly best practice though?
Georgia Brown
to be honest, not sure regarding "best practices", hence "IMO". i find it helpful to write code from the perspective of both the "producer" (me!) and the "consumer" (someone else, sometimes me!) and what each party (esp consumer!) *expects*. regardless of where one stands on practice however, `ref` explicitly states parameter may be modified by method, and in relation to WCF, that the contents should be transported back.
johnny g