Last active
January 18, 2019 08:45
-
-
Save lars-erik/20243fe06a8a85838af200a58ecc107d to your computer and use it in GitHub Desktop.
Making strings something readable and valuable automagically
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.ComponentModel; | |
using System.Globalization; | |
using System.Web.Mvc; | |
using Microsoft.Ajax.Utilities; | |
namespace StringTypes.Web.Controllers | |
{ | |
public class HomeController : Controller | |
{ | |
public ActionResult Index() | |
{ | |
return View(new PostModel{Reply = "Fresh model"}); | |
} | |
public ActionResult Submit(PostModel model) | |
{ | |
model.Reply = model.Input | |
? $"{model.Input} was posted" | |
: "Nothing was posted"; | |
return View("Index", model); | |
} | |
public ActionResult SubmitString(StringValue value) | |
{ | |
var model = new PostModel | |
{ | |
Input = value, | |
Reply = value | |
? $"{value} was posted" | |
: "Nothing was posted" | |
}; | |
return View("Index", model); | |
} | |
} | |
public class PostModel | |
{ | |
public StringValue Input { get; set; } | |
public StringValue Reply { get; set; } | |
} | |
[TypeConverter(typeof(StringValueConverter))] | |
public struct StringValue | |
{ | |
private readonly string value; | |
private StringValue(string value) | |
{ | |
this.value = value ?? ""; | |
} | |
private bool HasValue() | |
{ | |
return !value.IsNullOrWhiteSpace(); | |
} | |
public override string ToString() | |
{ | |
return value; | |
} | |
public static implicit operator bool(StringValue value) | |
{ | |
return value.HasValue(); | |
} | |
public static implicit operator string(StringValue value) | |
{ | |
return value.value; | |
} | |
public static implicit operator StringValue(string value) | |
{ | |
return new StringValue(value); | |
} | |
} | |
public class StringValueConverter : TypeConverter | |
{ | |
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) | |
{ | |
return sourceType == typeof(string); | |
} | |
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) | |
{ | |
return (StringValue)value?.ToString(); | |
} | |
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) | |
{ | |
return destinationType == typeof(StringValue); | |
} | |
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) | |
{ | |
return (StringValue)value?.ToString(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment