If you check out any of our previous WCF Tutorials, you'll notice all of the Service Contracts are implemented with interfaces containing only methods. For the longest time I thought that's all that was supported, until I thought about it a little more. In C# land, properties are simply wrappers around a get method and set method, so why wouldn't we be able to use properties in a service contract? Well the answer is we can.
Let's start by checking out the service contract we created for our interprocess communication tutorial.
public interface IStringReverser
{
[OperationContract]
string ReverseString(string value);
}
Let's add a property to this interface that retrieves the last string that was reversed.
public interface IStringReverser
{
string LastReversedString
{
get;
}
[OperationContract]
string ReverseString(string value);
}
Since the property doesn't have the OperationContract attribute, it won't be available through a WCF Service. You might initially think to just throw the attribute above the property, but doing so would result in this compile-time error:
That makes sense, since the property is not a method. What is a method, though, is the get portion of that property. This means, all we have to do is move the attribute to above the get keyword.
public interface IStringReverser
{
string LastReversedString
{
[OperationContract]
get;
}
[OperationContract]
string ReverseString(string value);
}
And there you have it, you now have a WCF service contract using properties. It's definitely better than having to implement separate get and set methods for each value.
08/11/2009 - 17:06
Thanks a lot dude. That small little trick worked out great.
You rock!
09/09/2009 - 15:28
thanks alot i's usefull:)
10/13/2009 - 02:00
very useful ,thanks
Add Comment
[language] [/language]
Examples:
[javascript] [/javascript]
[actionscript] [/actionscript]
[csharp] [/csharp]
See here for supported languages.
Javascript must be enabled to submit anonymous comments - or you can login.