Hewiiitt
Hewiiitt

Reputation: 306

How to add an operator function to a primative data type c#

So what I am trying to do is add an operator to a primitive data type that would work as follows.

int m_number = 10;
m_number.CheckCondition (1,10);

with the function CheckCondition working like so

public bool CheckCondition (<The m_number variable>,int t_lower,int t_upper);

Now I might be mistaken in this but I think I remember seeing a way of doing this but can no longer find it where the param: (The m_number variable) is something like

this <Word I Forgot> m_number

as the first param.

Does anyone know if this is possible and if so what I have to do.

Thanks in advance.

Upvotes: 1

Views: 48

Answers (1)

Ren&#233; Vogt
Ren&#233; Vogt

Reputation: 43886

You are looking for extensions. You can create it like that

public static class MyExtensions
{
    public static bool IsBetween(this int i, int lower, int upper)
    {
        return lower < i && upper > i;
    }
}

and then use it on any int:

bool check = 1.IsBetween(0, 10);

Note that since int is a value type, you cannot change it (like in i.ChangeSign() to change the actual value of i). You can only return a changed value if you need that.

Upvotes: 4

Related Questions