Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional Method Arguments on byte array

How would i make a default value for a byte array argument? The code below wont work...

public static void init(SomeByteArray[] = {1, 2, 3, 4}) {
    //Do Something
}

Is this possible?

Im doing this in .Net Micro Framework 4.1, if it makes any difference...

like image 537
Christian Bekker Avatar asked Jun 09 '13 18:06

Christian Bekker


People also ask

How do you use optional parameters?

A method that contains optional parameters does not force to pass arguments at calling time. It means we call method without passing the arguments. The optional parameter contains a default value in function definition. If we do not pass optional argument value at calling time, the default value is used.

How do you add optional parameters?

In the following example, I define the second parameter (secondNumber) as optional; Compiler will consider “0” as default value. Optional attribute always need to be defined in the end of the parameters list. One more ways we can implement optional parameters is using method overloading.

What is byte array?

ByteArray is an extremely powerful Class that can be used for many things related to data manipulation, including (but not limited to) saving game data online, encrypting data, compressing data, and converting a BitmapData object to a PNG or JPG file.


2 Answers

From MSDN:

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.

So an array instance cannot be used as default value.

The best solution is probbaly two define two overloads as follows:

public static void Init()
{
    Init(new byte[] { 1, 2, 3, 4 });
}

public static void Init(byte[] data)
{
    ...
like image 167
dtb Avatar answered Oct 27 '22 09:10

dtb


You can, but it needs to be assigned in the method, and the default value has to be null, like this:

public static void init(byte[] SomeByteArray = null)
{
    SomeByteArray = SomeByteArray ?? new byte[] {1, 2, 3, 4};
    //carry on with your method.
}
like image 25
It'sNotALie. Avatar answered Oct 27 '22 11:10

It'sNotALie.