Skip to content

Instantly share code, notes, and snippets.

@miklund
Created January 10, 2016 21:14
Show Gist options
  • Save miklund/7da52916024540dbfed8 to your computer and use it in GitHub Desktop.
Save miklund/7da52916024540dbfed8 to your computer and use it in GitHub Desktop.
2011-12-18 Failure of the dynamic keyword
# Title: Failure of the dynamic keyword
# Author: Mikael Lundin
# Link: http://blog.mikaellundin.name/2011/12/18/failure-of-the-dynamic-keyword.html
public class DynamicMatch : DynamicObject
{
private readonly Match match;
public DynamicMatch(Match match)
{
this.match = match;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
var prop = match.GetType().GetProperty(binder.Name);
// Match instance property
if (prop != null)
{
result = prop.GetValue(match, null);
return true;
}
// Group value
Group group;
if ((group = this.match.Groups[binder.Name]) != null)
{
result = group.Value;
return true;
}
result = null;
return false;
}
}
public class DynamicRegex
{
private readonly Regex expression;
public DynamicRegex(string expression)
{
this.expression = new Regex(expression);
}
public dynamic Match(string input)
{
return new DynamicMatch(expression.Match(input));
}
}
private static object GetEmployee()
{
return new { Name = "John", Profession = "Santa" };
}
object employee = GetEmployee();
private static dynamic GetEmployee()
{
dynamic employee = new { Name = "John", Profession = "Santa" };
return employee;
}
var employee = GetEmployee();
Console.WriteLine("Employee of the month: {0}, {1}", employee.Name, employee.Profession);
string time = "12:00";
var match = Regex.Match(time, @"(?<Hour>\d{2}):(?<Minute>\d{2})");
if (match.Success)
{
var hour = match.Groups["Hour"].Value;
var minute = match.Groups["Minute"].Value;
Console.WriteLine("The time is {0}.{1}", hour, minute);
}
string time = "12:00";
var match = new DynamicRegex(@"(?<Hour>\d{2}):(?<Minute>\d{2})").Match(time);
if (match.Success)
{
Console.WriteLine("The time is {0}.{1}", match.Hour, match.Minute);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment