Reputation: 6881
I have the following data member defined as part of a data contract that's passed from client to server for a WCF method. This data contract is used server-side; the clients are 3rd party vendors who most likely aren't even using WCF and are using Java clients, etc. This is a SOAP service.
[DataMember(Name = "PhoneType", IsRequired = false)]
public string PhoneType { get; set; }
I had thought that when IsRequired = false
is set, that means you can completely omit the element from the SOAP request AND the value for PhoneType would default to String.Empty
. However, that's not happening.
I realized this when I was using lead.PhoneType.Equals(somestring)
and hit an exception because lead.PhoneType
was a null reference. Of course the easy fix is to check for NULL first, but why would it be null in the first place? What I found is if you include <ns:PhoneType />
in the SOAP request, then lead.PhoneType
is set to String.Empty
, but if you completely exclude that element from the request, then lead.PhoneType
is null. Shouldn't is default to String.Empty
? Am I misunderstanding something about how WCF treats optional data members that are not included in the request?
Upvotes: 0
Views: 1134
Reputation: 7344
If a string variable is declared but not set, it will be null and not string.Empty. That's the way the language works.
In .NET, strings are Reference types not Value types and so do not have a default value. Without a default value, the value is null. This is as it should be.
Upvotes: 1