views:

417

answers:

2

I have a contract as follows:

[DataContract]
public class MyObj
{
    [DataMember(IsRequired=true)]
    public string StrA {get; private set;}

    [DataMember(IsRequired=false)]
    public string StrB {get; private set;}
}

What exactly does IsRequired mean? Does IsRequired=false mean that I can pass an instance of MyObj across the wire with StrB unitialized or does it mean that I can pass an instance of MyObj across the wire with StrB absent?

If the latter, how do I actually instantiate + send across an instance of MyObj without StrB?

A: 

DataMember's IsRequired tells the serialization engine whether the value of StrB must be presented in the underlying XML.

So over the wire you can get <MyObj></MyObj> and it will deserialize into an MyObj instance just fine.

Edit: You can't actually initialize a instance of MyObj without StrB being present. The use for this is compatibility and extensibility. For example, maybe the client doesn't have the updated MyObj version and it doesn't have StrB present. In this case, the server code can mark StrB as not requried and there will not be a serialization exception when a message is received on the server side.

siz
ok, so given my class above I could send across <MyObj><StrA>abc</StrA></MyObj> - thats what you're saying, right? If so how do I instantiate MyObj with StrA but not StrB..??
Tamim Sadikali
Yes, that's what I'm saying. I don't know if your DataContract will work though. I'm not sure whether DataMember requires public getter/setter. You cannot instantiate MyObj with StrA but not StrB using the code above. If you create another version of MyObj that does not contain StrB, then you could.
siz
A: 

how do I actually instantiate + send across an instance of MyObj without StrB?

As I just mentioned in http://stackoverflow.com/questions/1567173/wcf-and-anonymous-types , you can use [DataMember(EmitDefaultValue=false)]. This will make sure that when the data member is at its default value (e.g. null for strings), it won't be emitted.

Eugene Osovetsky