Skip to content

Instantly share code, notes, and snippets.

@zplume
Last active December 20, 2015 03:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zplume/6061955 to your computer and use it in GitHub Desktop.
Save zplume/6061955 to your computer and use it in GitHub Desktop.
Reflection, Linq & Properties demo
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using LS.Extensions;
using Properties;
namespace Properties
{
class Program
{
static void Main(string[] args)
{
ColourWrapper colour = new ColourWrapper();
// access properties with dot notation
var propA = colour.Red;
var propB = colour.Blue;
// get all properties of Type 'Colour', return as a List<Colour> and output to the console
colour.GetPropertiesOfType<Colour>().ForEach(p => Console.WriteLine(p.R + ", " + p.G + ", " + p.B));
}
}
class ColourWrapper
{
// properties we want to access using reflection extension method:
public Colour Red { get; set; }
public Colour Green { get; set; }
public Colour Blue { get; set; }
// constructor
public ColourWrapper()
{
// set the values of the class properties
Red = new Colour(255, 0, 0);
Green = new Colour(0, 255, 0);
Blue = new Colour(0, 0, 255);
}
}
class Colour
{
public int R { get; set; }
public int G { get; set; }
public int B { get; set; }
public Colour(int r, int g, int b)
{
R = r;
G = g;
B = b;
}
}
}
namespace LS.Extensions
{
public static class GenericMethods
{
/// <summary>
/// Returns a generic list of object property values that match the supplied type
/// </summary>
/// <typeparam name="T">The type of property values to return</typeparam>
/// <returns>A generic list of property values that match the supplied type</returns>
public static List<T> GetPropertiesOfType<T>(this Object classInstance)
{
return classInstance.GetType()
.GetProperties()
.Where(p => p.PropertyType == typeof(T)) // filter by type
.Select(p => p.GetValue(classInstance, null)) // get values
.Cast<T>() // cast to appropriate type
.ToList(); // output as List<T>
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment