Full implementation is here https://gist.github.com/1306491
I’m using struct with implicit casting to implicitly convert to and from source type and describes check rule through generic parameters of the struct.
From my point of view it can reduce code repetition and can be read as an dsl.
How to use:
static void Main(string[] args)
{
string s = Size(null);//result: argument exception
Console.WriteLine(Lenght(null));//result 0
DivByZero(0);// result: argument exception
Log(5);//result: log 5 to console
AddTenSymbols("");//result: if result string has lenght more than 10 then log result string/
Console.ReadKey();
}
static Check<string, IsNotNull<string>> Size(Check<object, IsNotNull<object>> obj)
{
return obj.ToString();
}
static int Lenght(Check<string, AndReplaceByEmptyIfNull> str)
{
string stri = str;
return stri.Length;
//return ((string)str).Length;
}
static int DivByZero(Check<int, If<int, EqualsTo<Zero>, ThenThrowArgumentException<int>>> i)
{
return 1 / i;
}
static Check<int, If<int, BothTrue<Not<EqualsTo<Zero>>, Not<MoreThan<Ten>>>, ThenLog<int>>> Log(int i)
{
return i;
}
static Check<string, If<string, Member<string, int, StringLenght, MoreThan<Ten>>, ThenLog<string>>> AddTenSymbols(string s)
{
return s + "asffgsdfgd"; ;
}
To answer the title-question: No, don’t do that. Implicit casting should be safe and not throw.
From the C# Language specification, § 6.1 :
So if you do want validation, make it an explicit conversion.