Home > .NET Development > >C# – Getting Property value of an object using extension method

>C# – Getting Property value of an object using extension method


>Code below illustrate how to process a list of T and validating or checking the value of one of the property of object T using C# 3.0 extension methods.

/// <summary>

/// Method that returns Value of Property from an Object
/// </summary>
/// <param name=”obj”></param>
/// <param name=”propertyName”></param>
/// <returns></returns>
public static string GetPropertyValue(this object obj, string propertyName)
{
if (obj == null)
{
throw new ArgumentNullException(“obj”);
}
PropertyInfo propertyInfo = obj.GetType().GetProperty(propertyName);
if (propertyInfo != null)
{
object prop = propertyInfo.GetValue(obj, null);
return prop.ToString();
}
else
{
return string.Empty;
}
}
 
 
Sample Usage:

/// <summary>

//////</summary>
[TestMethod()]
public void GetPropertyValueTest()
{
List<TestClass > list = new List<TestClass>
{
new TestClass
{
GUID = “Not this value”
},
new TestClass
{
GUID = “ThisValue”
}
};
ProcessList(list);
}


private void ProcessList<T>(List<T> list) where T: class
{
//Check the value of certain property in T object
var query = list.Find(i => i.GetPropertyValue(“GUID”) == “ThisValue”);
if(query != null)
{
//Match Found.. Do processing here
}
else
{
//No Match found..
}
}

Advertisements
Categories: .NET Development Tags:
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: