Difference between revisions of "C"

From Richard's Wiki
Jump to: navigation, search
(Get Property Name via Lambda Expression)
Line 3: Line 3:
 
===== Get Property Name via Lambda Expression =====
 
===== Get Property Name via Lambda Expression =====
  
To use it do something like GetPropertyName(()=>this.Property);
+
To use it do something like this.PropertyName(()=>this.Property);
  
 
<code>
 
<code>
Line 9: Line 9:
 
  using System.Linq.Expressions;
 
  using System.Linq.Expressions;
 
  using System.Reflection;
 
  using System.Reflection;
  private string GetPropertyName<T>(Expression<Func<T>> property)
+
  private string PropertyName<T>(Expression<Func<T>> property)
 
  {
 
  {
 
     var propertyInfo = (property.Body as MemberExpression).Member as PropertyInfo;
 
     var propertyInfo = (property.Body as MemberExpression).Member as PropertyInfo;
Line 20: Line 20:
 
  }
 
  }
 
</code>
 
</code>
 
  
 
===== SerializeToXml =====
 
===== SerializeToXml =====

Revision as of 23:36, 25 July 2011

Get Property Name via Lambda Expression

To use it do something like this.PropertyName(()=>this.Property);

using System;
using System.Linq.Expressions;
using System.Reflection;
private string PropertyName<T>(Expression<Func<T>> property)
{
    var propertyInfo = (property.Body as MemberExpression).Member as PropertyInfo;
    if (propertyInfo == null)
    {
      throw new ArgumentException("The lambda expression 'property' should point to a valid Property");
    }
    var propertyName = propertyInfo.Name;
    return propertyName;
}

SerializeToXml
       using System.IO;
       using System.Xml;
       /// <summary>
       /// Serializes to XML.
       /// </summary>
       /// <param name="firstClassElement">The first class element to serialize.</param>
       /// <returns>The XML string that represents the passed first class element.</returns>
       public virtual string SerializeToXml(FirstClassElementType firstClassElement)
       {
           string xmlData;
           var memoryStream = new MemoryStream();
           XmlTextWriter writer = null;
           try
           {
               writer = new XmlTextWriter(memoryStream, Encoding.Unicode)
                            {
                                Formatting = Formatting.Indented,
                                Indentation = 0
                            };
               var xmlSerializer = new XmlSerializer(typeof (FirstClassElementType));
               xmlSerializer.Serialize(writer, firstClassElement);
               writer.Flush();
           }
           finally
           {
               memoryStream.Seek(0, SeekOrigin.Begin);
               var textReader = new StreamReader(memoryStream);
               xmlData = textReader.ReadToEnd();
               textReader.Close();
               if (null != writer)
                   writer.Close();
           }
           return xmlData;
       }