Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare default property for a struct

Tags:

c#

.net

vb.net

I want to create my own Integer with struct.

Here is a simple example of a Integer which the return value is forced to between 0 and 255.

These are pseudocode and C# won't compile it.

struct MyInt{
    private int p;
    default property theInt{  
        set{
            p = value;
        }
        get{
            if(p > 255) return 255; else if( p < 0) return 0;
            return p;
        }
    }
}

My main goal is to use following code :

MyInt aaa = 300;            //Grater than 255
if(aaa == 255) aaa = -300;  //Less than 255
if(aaa == 0) a = 50;

Is this possible to do with any .NET language ? Of course I prefer C#

like image 510
Mohsen Sarkar Avatar asked Dec 11 '25 20:12

Mohsen Sarkar


1 Answers

As I said in my comment, you can use an implicit conversion between your structure and int:

internal struct MyInt
{
    private int p;

    public int BoundedInt
    {
        // As CodesInChaos points out, the setter is not required here.
        // You could even make the whole property private and jsut use
        // the conversions.
        get
        {
            if (p > 255) return 255;
            if (p < 0) return 0;
            return p;
        }
    }

    public static implicit operator int(MyInt myInt)
    {
        return myInt.BoundedInt;
    }

    public static implicit operator MyInt(int i)
    {
        return new MyInt { p = i };
    }
}

You need both the int-to-struct conversion for when you assign a value and the struct-to-int conversion for when you compare values.

like image 89
Rawling Avatar answered Dec 14 '25 11:12

Rawling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!