Skip to content

Instantly share code, notes, and snippets.

@DanielMPries
Last active October 22, 2017 00:55
Show Gist options
  • Save DanielMPries/663566c621e39e315128d7da3151f18f to your computer and use it in GitHub Desktop.
Save DanielMPries/663566c621e39e315128d7da3151f18f to your computer and use it in GitHub Desktop.
Demonstrates the With keyword implementation similar to VB.NET using a generic extension method
using System;
namespace Sandbox {
class Program {
static void Main(string[] args) {
var someLongNamedVariableName = new Person();
// Notice that the parent object is marked with two underscores "__"
// and the child with a single underscore "_". This is because the
// double underscore created in the outer anonymous Action lamda
// shares scope with the inner anonymous Action lambda so it requires
// a different variable name to shorthand the reference
someLongNamedVariableName.With(__ => {
__.Name = new Name();
__.Name.With(_ => {
_.First = "Michael";
_.Middle = "Sylvester";
_.Last = "Stallone";
_.Prefix = "Mr.";
_.Suffix = string.Empty;
});
__.DateOfBirth = DateTime.ParseExact("07/06/1946", "MM/dd/yyyy", null);
Console.WriteLine( __.Name.GetNameAsReferenceString());
Console.WriteLine(__.GetNameAndDateOfBirth());
});
Console.Read();
}
}
public static class ObjectExtentions {
/// <summary>
/// Performs an action using the defined object, specifically
/// for the added ablility to perform shorthand object name aliasing
/// </summary>
/// <typeparam name="T">The object type</typeparam>
/// <param name="obj">The object</param>
/// <param name="action">The action</param>
public static void With<T>(this T obj, Action<T> action) where T : class {
action(obj);
}
}
internal class Name {
public string Prefix { get; set; }
public string First { get; set; }
public string Middle { get; set; }
public string Last { get; set; }
public string Suffix { get; set; }
public string GetNameAsReferenceString() {
return $"{Last}, {First} {Middle.Substring(0, 1)}";
}
}
internal class Person {
public Name Name { get; set; }
public DateTime DateOfBirth { get; set; }
public string GetNameAndDateOfBirth() {
return $"{Name.First} {Name.Last} {DateOfBirth:D}";
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment