I have the model class like the following,
public class Station
{
[DataMember (Name="stationName")]
public string StationName;
[DataMember (Name="stationId")]
public string StationId;
}
I would like to get the Name of DataMember
with Property Name, i.e If I have the property name "StationName", How can I get the stationName
?
Data Member are the fields or properties of your Data Contract class. You must specify [DataMember] attribute on the property or the field of your Data Contract class to identify it as a Data Member. DataContractSerializer will serialize only those members, which are annotated by [DataMemeber] attribute.
A datacontract is a formal agreement between a client and service that abstractly describes the data to be exchanged. In WCF, the most common way of serialization is to make the type with the datacontract attribute and each member as datamember.
[DataContract] attribute specifies the data, which is to serialize (in short conversion of structured data into some format like Binary, XML etc.) and deserialize(opposite of serialization) in order to exchange between the client and the Service.
EmitDefaultValue. DataMember EmitDefaultValue is a Boolean attribute with the default value of true. If the value is not provided for DataMember then the corresponding default value will be set to the member for example integer it will be set as 0, for bool it is false, any reference type is null.
A slight modification to your class
[DataContract]
public class Station
{
[DataMember(Name = "stationName")]
public string StationName { get; set; }
[DataMember(Name = "stationId")]
public string StationId { get; set; }
}
and then this is how you can get it
var properties = typeof(Station).GetProperties();
foreach (var property in properties)
{
var attributes = property.GetCustomAttributes(typeof(DataMemberAttribute), true);
foreach (DataMemberAttribute dma in attributes)
{
Console.WriteLine(dma.Name);
}
}
I created an extension method:
public static string GetDataMemberName(this MyClass theClass, string thePropertyName)
{
var pi = typeof(MyClass).GetProperty(thePropertyName);
if (pi == null) throw new ApplicationException($"{nameof(MyClass)}.{thePropertyName} does not exist");
var ca = pi.GetCustomAttribute(typeof(DataMemberAttribute), true) as DataMemberAttribute;
if (ca == null) throw new ApplicationException($"{nameof(MyClass)}.{thePropertyName} does not have DataMember Attribute"); // or return thePropertyName?
return ca.Name;
}
with usage
myInstance.GetDataMemberName(nameof(MyClass.MyPropertyName)))
You can do it simply by using the Reflection
, cast
that return attribute to DataMemberAttribute
class and read the Name property value
.
Here is a complete 3rd party example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With