You can accomplish this by overloading the implicit conversion (casting) operator. For instance:
class MyDynType : System.Dynamic.DynamicObject
{
public int Value { get; set; }
public static implicit operator MyDynType(int value)
{
MyDynType x = new MyDynType();
if (value > 100)
x.Value = 100;
else
x.Value = value;
return x;
}
}
Then you can use it like this:
dynamic x = (MyDynType)6;
Console.WriteLine(x.Value); // Outputs "6"
dynamic y = (MyDynType)150;
Console.WriteLine(y.Value); // Outputs "100"
For more info, see the MSDN page. Since you tagged VB.NET, I'll mention that the equivalent in VB.NET is to overload the CType
operator using Widening
modifier.
However, overloading the conversion operators can cause a lot of confusion, so you should do so sparingly, if at all.