Articles → WCF → Using Enums In WCF Service

Using Enums In WCF Service






Prerequisite


  1. First of all create a WCF service application.
  2. From the application remove code from interface and class so your interface and class will be
  3. [ServiceContract]
    public interface IService1 {}




    public class Service1: IService1 {}


  4. Next step is to create an application that will consume the service. For this article, I am creating a console application.
  5. Last step is adding the service reference. But right now it is not possible because your interface does not have any code. So we will add the reference once we have some method inside our interface.



Steps


  1. The first step is to create an enum in IService1 interface. The syntax will be
  2. [DataContract]
    public enum enum_name {
      [EnumMember]
      enum1,
      [EnumMember]
      enum2
    }




    [ServiceContract]
    public interface IService1 {}
    
    [DataContract]
    public enum enum_name {
      [EnumMember]
      enum1,
      [EnumMember]
      enum2
    }


  3. The second step is to add a new DataContract and add enum as DataMember. See the following code.
  4. [ServiceContract]
     public interface IService1 {}
    
     [DataContract]
     public enum enum_name {
       [EnumMember]
       enum1,
       [EnumMember]
       enum2
     }
    
     [DataContract]
     public class CompositeType {
       [DataMember]
       public enum_name MyEnum {
         get;
         set;
       }
     }


  5. Last step will be to create the signature of the method in IService1 interface and pass CompositeType as a parameter. See the following code.
  6.  [ServiceContract]
     public interface IService1 {
       void DisplayData(CompositeType ct);
     }
    
     [DataContract]
     public enum enum_name {
       [EnumMember]
       enum1,
       [EnumMember]
       enum2
     }
    
     [DataContract]
     public class CompositeType {
       [DataMember]
       public enum_name MyEnum {
         get;
         set;
       }
     }




public class Service1: IService1 {
  public void DisplayData(CompositeType ct) {
    throw new NotImplementedException();
  }
}



Back To Client Application




Picture showing the output of using enums in WCF service
Click to Enlarge


Posted By  -  Karan Gupta
 
Posted On  -  Tuesday, May 19, 2015

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250