I recently came across an issue where i cannot have optional parameters in function in a WinRT project.
Are there any alternatives to this ? I even tried the [optional] keyword. Does not work.
I recently came across an issue where i cannot have optional parameters in function in a WinRT project.
Are there any alternatives to this ? I even tried the [optional] keyword. Does not work.
In Windows runtime component project public functions cannot have optional parameters only private functions can have them.
But if you convert that project to a class library, even for public functions you can have optional parameters.
An other possible approach : use an overrided signature.
public void TheFunction (string param1, string param2)
{
[...] //processing stuff
}
public void TheFunction (string param1)
{
return TheFunction(param1, String.Empty);
}
The following will not compile:
void PrintStuffOptional(string stuff, [Optional] int num)
{
Console.WriteLine(stuff + ": " + num.ToString());
}
Resulting in:
The type or namespace name 'Optional' could not be found (are you missing a using directive or an assembly reference?)
and/or:
The type or namespace name 'OptionalAttribute' could not be found (are you missing a using directive or an assembly reference?)
Adding using System.Runtime.InteropServices;
at the top of your file should correct those issues. However, as of C# 4.0, you can declare optional parameters like so:
void PrintStuff(string stuff, int num = 0)
{
Console.WriteLine(stuff + ": " + num.ToString());
}
If the calling method does not provide a value for the num
parameter, it will use the default value of 0
. Therefore, the void PrintStuff()
will work both ways:
PrintStuff("a string to print");
PrintStuff("a string to print", 37239);