Friday, April 10, 2009

Using Generic List in WCF

Scenario:
I wanted to store few documentIDs in my DataMember. I thought of using Generic List, so far so good but when adding the service reference from my client application, I noticed that Generic List got converted to string[] and while compiling I got the following error

Cannot implicitly convert type 'string[]' to System.Collections.Generic.List'

Workaround:
The representation of a List is equivalent to the representation of a ArrayList. So it will just work if you use the Arraylist at the client side

Solution:
Right click the Service reference > Configure Service Reference > Select 'System.Collection.Generic.List' from Collection type drop down menu.

But i wanted to still use Generic List, so this is how i did it.
Here's the code.

IService1.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

using System.Collections;

namespace TestWCF
{
[ServiceContract]
public interface IService1
{
[OperationContract]
CompositeType GetDataUsingDataContract(CompositeType composite);
}

[DataContract]
public class CompositeType
{
private List<string> lists;
[DataMember]
public List<string> Lists
{
get { return lists; }
set { lists = value; }
}
}
}
Service1.cs:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace TestWCF
{
public class Service1 : IService1
{
public CompositeType GetDataUsingDataContract(CompositeType composite)
{
composite.Lists = new List<string>();
composite.Lists.Add("D");

return composite;
}
}
}
Code:
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace TestWCFClient
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
ServiceReference1.CompositeType composite = new ServiceReference1.CompositeType() ;
ServiceReference1.CompositeType composite2 = new ServiceReference1.CompositeType() ;

ServiceReference1.Service1Client sc = new ServiceReference1.Service1Client();
composite2 = sc.GetDataUsingDataContract(composite);
MessageBox.Show(composite2.Lists.Count.ToString());
}
}
}

0 comments: