Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set default parameter value to BigInteger type?

Tags:

c#

biginteger

I need to have a class that has a constructor with BigInteger type. I'd like to set a default value to 0 to it with this code, but I got compile error.

public class Hello
{
    BigInteger X {get; set;}
    public Hello(BigInteger x = 0)
    {
        X = x;
    }
}

public class MyClass
{
    public static void RunSnippet()
    {
        var h = new Hello(); // Error <-- 

What's wrong? Is there way to set default value to BigInteger parameter?

like image 750
prosseek Avatar asked Dec 22 '22 08:12

prosseek


2 Answers

Default parameters only work compile time constants (and value types where the parameter can be default(ValType) or new ValType()), and as such don't work for BigInteger. For your case, you could perhaps do something like this; providing a constructor overload that takes int, and make that have a default parameter:

public Hello(int x = 0) : this(new BigInteger(x)) {}
public Hello(BigInteger x) 
{
    X = x;
}

In case you are wondering, the x = 0 doesn't count as a constant when the type is a BigInteger, because converting 0 to BigInteger would involve invoking the implicit conversion operator for int to BigInteger.

like image 63
driis Avatar answered Dec 28 '22 23:12

driis


In this particular case, since the default value you want is zero, you can use the default BigInteger constructor because BigInteger is a value type:

public class Hello
{
    BigInteger X { get; set; }

    public Hello(BigInteger x = new BigInteger())
    {
        X = x;
    }
}

This will not work with values besides zero because the expression must be a compile time constant:

Each optional parameter has a default value as part of its definition. If no argument is sent for that parameter, the default value is used. A default value must be one of the following types of expressions:

  • a constant expression;
  • an expression of the form new ValType(), where ValType is a value type, such as an enum or a struct;
  • an expression of the form default(ValType), where ValType is a value type.
like image 40
Rick Sladkey Avatar answered Dec 28 '22 22:12

Rick Sladkey