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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With