Created
April 6, 2012 04:16
-
-
Save masaru-b-cl/2316794 to your computer and use it in GitHub Desktop.
My LimitedString with implicit cast to string
This file contains hidden or 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; | |
namespace ConsoleApplication1 | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var ls = LimitedString.Create(5); | |
ls.Value = "12345"; | |
Console.WriteLine(ls); | |
var str = ls; | |
Console.WriteLine(str); | |
try | |
{ | |
ls.Value = "123456"; | |
Console.WriteLine("Fail"); | |
} | |
catch (ArgumentException ex) | |
{ | |
Console.WriteLine("Success"); | |
Console.WriteLine(ex.Message); | |
} | |
} | |
} | |
class LimitedString | |
{ | |
private uint _length; | |
private LimitedString(uint length) | |
{ | |
this._length = length; | |
} | |
public static LimitedString Create(uint length) | |
{ | |
return new LimitedString(length); | |
} | |
private string _value; | |
public string Value | |
{ | |
get | |
{ | |
return _value; | |
} | |
set | |
{ | |
if ((value ?? "").Length > _length) | |
{ | |
throw new ArgumentException( | |
String.Format("入力文字列の長さが{0}を超えています", this._length) | |
); | |
} | |
this._value = value; | |
} | |
} | |
public override string ToString() | |
{ | |
return this._value; | |
} | |
public static implicit operator string(LimitedString ls) | |
{ | |
return ls._value; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment