marvin
marvin

Reputation: 1925

Function to get different types of input?

I have a BigInt class in C#, which has functions like

public BigInt Multiply(BigInt Other)
public BigInt Exponentiate(BigInt Other)

etc. and BigInt can be constructed with strings or ints, that's ok to have more than one constructors. But when I want to call these arithmetic functions with int's (instead of BigInt's) like

this.Multiply(int a);

I have to re-define the same Multiply function with input int like

public BigInt Multiply(int other)
{
BigInt Other = new BigInt(other);
//rest of the code same
}

so how can I handle this in one piece of code? I think default parameters will allow only one of these (e.g. just BigInt but not int or vice versa).

Thanks in advance..

Upvotes: 0

Views: 202

Answers (2)

user1610015
user1610015

Reputation: 6678

How about just implementing each int overload in terms of the BigInt one?:

public BigInt Multiply(int a)
{
    return Multiply(new BigInt(a));
}

Upvotes: 1

Lee
Lee

Reputation: 144206

Create an implicit conversion from int to BigInt

public static implicit operator BigInt(int value)
{
    return new BigInt(value);
}

then you only need an overload which takes a BigInt parameter:

BigInt bigInt = ...
BigInt mult = bigInt.Multiply(5);

Upvotes: 3

Related Questions