Reflection, Linq & Properties demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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