5

I have a very simple class called person.

public class Person{
   [DataMember(Name="MyName")]
   public string Name { get;set;}
}

If I try to serialize or de-serialize, everything works great. In the XML I can see a tag called "MyName" and in the object I see with the VS Intellisense a property called Name.

What I need now is to access, from the object, the serialized name of the property.

For example, I can do object.GetType().GetProperty("Name"); but if I try to do object.GetType().GetProperty("MyName"), the reflection says that the property does not exist. How I can read the serialized name of the property? Is there a way?

peterh
  • 11,875
  • 18
  • 85
  • 108
Raffaeu
  • 541
  • 1
  • 3
  • 9
  • Are you trying to do this from the service side or the client side? – Tad Donaghe Jan 18 '10 at 19:46
  • From client side, and there is no way with the DataContractSerializer to read the attribute of the property. I tried also with XDocument and Linq. Any suggestions? – Raffaeu Jan 18 '10 at 19:53

1 Answers1

3

It seems that the only way is to access, using reflection, the attributes of the property in this way:

var att = myProperty.GetType().GetAttributes();
var attribute = property.GetCustomAttributes(false)[0] as DataMemberAttribute;
Console.WriteLine(attribute.Name);

This works on both, client and server, without the need of serialize and deserialize the object.

Raffaeu
  • 541
  • 1
  • 3
  • 9
  • 1
    some null checking may be in order, your answer assumes only one attribute, try checking like so: `var attribute = (DataMemberAttribute)propertyInfo.GetCustomAttributes(typeof(DataMemberAttribute),false).FirstOrDefault(); if (attribute != null) name = attribute.Name;` – Myster Apr 23 '12 at 04:24