WCF DataContract - marking member IsRequired=false
Asked Answered
M

2

5

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?

Murderous answered 14/10, 2009 at 14:50 Comment(0)
H
3

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.

Hypergolic answered 14/10, 2009 at 14:53 Comment(2)
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..??Murderous
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.Hypergolic
F
2

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

As I just mentioned in 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.

Feoffee answered 14/10, 2009 at 16:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.