Victor
Victor

Reputation: 14583

Declaring new types

Let's suppose that I have the following class:

class Number{

}

I want then to declare variables of Number type, and give them a value like in int or uint or any kind of variables:

Number n = 14;

I am not sure if my question is good, but please help me, because I am new in C#

Upvotes: 1

Views: 86

Answers (3)

user1610015
user1610015

Reputation: 6678

You can overload operators in your class:

class Number
{
    public static Number operator=(int i)
    {
        ...
    }
}

BTW, for simple and small classes like this, it's better to use structs, not classes.

Upvotes: 1

Matt Burland
Matt Burland

Reputation: 45135

You want to look at implicit to create an implicit conversion from int to your number class.

Upvotes: 1

cdhowie
cdhowie

Reputation: 168998

You can create implicit conversion operators to handle cases like this. Your class needs a constructor that the implicit conversion operator will call. For example:

class Number
{
    public int Value { get; set; }

    public Number(int initialValue)
    {
        Value = initialValue;
    }

    public static implicit operator Number(int initialValue)
    {
        return new Number(initialValue);
    }
}

Then the line

Number n = 14;

Will be effectively equivalent to

Number n = new Number(14);

You can add an operator to the class to go in the other direction too:

public static implicit operator int(Number number)
{
    if (number == null) {
        // Or do something else (return 0, -1, whatever makes sense in the
        // context of your application).
        throw new ArgumentNullException("number");
    }

    return number.Value;
}

Be careful with implicit operators. They are nice syntactic sugar, but they can also make it harder to tell what's really going on in a particular chunk of code. You can also use explicit operators, which require a type-cast to invoke.

Upvotes: 7

Related Questions