How to pass complex object to WCF service.
Send complex data to WCF service
In this article we will see how to send complex data to WCF
service. This article demands that you have basic understanding of WCF. Let’s
see how to send a complex object to WCF service.
At first we have to create one WCF service. Then we will
create one client (console application) to send data to service.
Create WCF service
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace NameService
{
[ServiceContract]
public interface IStringAdd
{
[OperationContract]
string AddName(Person tmp);
}
[DataContract]
public class Person
{
public string Name;
public string Surname;
[DataMember]
public string pName
{
get { return Name;}
set { Name = value; }
}
[DataMember]
public string pSurName
{
get { return Surname; }
set { Surname = value; }
}
}
}
At first we have created IStringAdd interface which has
AddName() method. Then we have created DataContract which is nothing but normal
C# class containing two properties called Name and Surname.
We have specified DataMember to the property of Person
class. Now we have to create one class to implement IStringAdd interface. In
below we have defined class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace NameService
{
public class StringAdd : IStringAdd
{
public string AddName(Person tmp)
{
return "Hi " + tmp.Name + " " + tmp.Surname;
}
}
}
We have implemented AddName() function which will take
object of Person class. Within this function we are adding name and surname of
Person class. This message will return to client.
Create client to consume service.
Now, we have to create one client to consume service. Let’s
create one console application to consume service.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Client.NameService;
namespace Client
{
class Program
{
static void Main(string[] args)
{
IStringAdd obj = new StringAddClient();
NameService.Person objPerson = new Person();
objPerson.pName = "Sourav ";
objPerson.pSurName = "Kayal";
Console.WriteLine(obj.AddName(objPerson));
Console.ReadLine();
}
}
}
In Main() function we are creating object of StringAddClient
class and we are passing object of Pseson class to AddName() method.
Here is output of this application

Conclusion :-
In this article we have seen how to send complex object to WCF service from client application. Hope you have understood the concept.