Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WCF DataContract - marking member IsRequired=false

Tags:

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?

like image 474
Tamim Sadikali Avatar asked Oct 14 '09 14:10

Tamim Sadikali


1 Answers

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.

like image 112
Szymon Rozga Avatar answered Oct 12 '22 15:10

Szymon Rozga