Exposing Enums In WCF To Client Application

This article explains how to expose enums used in WCF Service to the clients who consume our Service.

Create a WCF Service and create an enum inside it.

  1. [DataContract]  
  2.     public enum Status  
  3.     {  
  4.         [EnumMember]  
  5.         Open,  
  6.         [EnumMember]  
  7.         InProgress,  
  8.         [EnumMember]  
  9.         Done,  
  10.         [EnumMember]  
  11.         Close  
  12.     }  
We need to decorate enum with [DataContract] attribute and each member with [EnumMember] attribute, if we want them to be visible on the client end. These attributes can be found in System.Runtime.Serialization namespace.
 
We just need to make sure that we use that enum in our WCF Service, otherwise you will not find it on the client side. Below we have defined GetDataStatus as an operation contract, which takes our Status enum as a parameter. 
  1. [ServiceContract]  
  2.     public interface IService1  
  3.     {  
  4.         [OperationContract]  
  5.         string GetDataStatus(Status state);  
  6.           
  7.     }  
Following is the implementation of GetDataStatus method in class, which implements IService1 interface. 
  1. public class Service1 : IService1  
  2.     {  
  3.         public string GetDataStatus(Status state)  
  4.         {  
  5.             if (state == Status.Open)  
  6.             {  
  7.                 return "Status Open";  
  8.             }  
  9.             if (state == Status.Done)  
  10.             {  
  11.                 return "Status Done";  
  12.             }  
  13.             return string.Empty;  
  14.         }  
  15.     }  
Now, we are done with our WCF Service. We need an application which consumes WCF Service. For this, I have created a console application and added reference of our WCF Service in it and written the code given below in it. 
  1. class Program  
  2.     {  
  3.         static void Main(string[] args)  
  4.         {  
  5.             ServiceReference1.Service1Client sc = new ServiceReference1.Service1Client();  
  6.             Console.WriteLine(sc.GetDataStatus(ServiceReference1.Status.Open));  
  7.             Console.ReadKey();  
  8.         }  
  9.     }  
You will find that we will be able to access our Status enum on line number 06 above.

Thanks for reading and you can find the source code attached, which is used in this article.
Ebook Download
View all
Learn
View all