Question

I'm trying to create my own data type.
So I started with a base example of Microsoft DynamicDictionary.

The code is : at http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.aspx

Main part of my type

public class myDynType : System.Dynamic.DynamicObject
{
    ....
}

Now I want something like this in my code :

[MaxAllowedValue(100)]
myDynType  SomeVar;

As you know we can't overload assignment in C# (= operator) so what are alternative ways to fire a event before assignment and after that ?

SomeVar = 7.55;   // I want to fire an event right before assignment
//Plus after assignment 

I want to check the value before assignment to throw an exception if it's bigger than 100. And I want to check it after assignment to round the value or modify it.

Was it helpful?

Solution 2

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.

OTHER TIPS

Not exactly, but maybe you can do what you need with properties:

myDynType someVar;
[MaxAllowedValue(100)]
myDynType SomeVar
{
    get
    {
        return someVar;
    }
    set
    {
        PreStuff();
        someVar = value;
        PostStuff();
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top