xsharp.eu • Optional parameters from X# to C#
Page 1 of 1

Optional parameters from X# to C#

Posted: Wed Jan 01, 2025 2:30 pm
by baramuse
Hi and a very happy new year to everyone !

I stumble upon a strange behaviour when calling c# functions from a x# project:

I have a c# function having an optional string parameter with a default value:

Code: Select all

public static void DefaultParameterTest(string defautvalue = "default")
{
    Console.WriteLine($"DefaultParameterTest: {defautvalue}");
}
If I call the function with a string, all good.
If I call this function from x# without a parameter, all good it prints the default string value
Now if I call the function with a null variable, when debugged on the c# side, a empty string is provided !
To be noted, I'm not using the "initialize string" compilation otion (/vo2)
Also having the same behaviour when using a USUAL parameter, directly passing null !

Code: Select all

    LOCAL nullString := NULL AS STRING 
    LOCAL nullUsual := NULL AS USUAL 
    DefaultParmeterValue.Class1.DefaultParameterTest("this is expected")
    DefaultParmeterValue.Class1.DefaultParameterTest()
    DefaultParmeterValue.Class1.DefaultParameterTest(nullString)
    DefaultParmeterValue.Class1.DefaultParameterTest(nullUsual)
    DefaultParmeterValue.Class1.DefaultParameterTest(NULL)
    
    ==> 
    
DefaultParameterTest: this is expected
DefaultParameterTest: default
DefaultParameterTest:
DefaultParameterTest:
DefaultParameterTest:
Cheers !

Re: Optional parameters from X# to C#

Posted: Thu Jan 02, 2025 10:09 am
by Chris
Hi Basile,

Happy New Year to you, too!

The string data type in .Net is a reference type (like Form, DataWindow, ArrayList etc or any CLASS you declare and unlike value types like INT, LOGIC etc), so assigning NULL to a string var, or passing NULL to a string parameter is valid and sets that var/parameter to NULL. It may appear as an empty string when printing it, but its value is actually NULL. You can see this by adding this to the c# method:

Code: Select all

Console.WriteLine(defautvalue == "");
Console.WriteLine(defautvalue == null);

Re: Optional parameters from X# to C#

Posted: Thu Jan 02, 2025 11:42 am
by baramuse
Hi Chris !

and thanks for your answer but my understanding was that if I do pass a NULL to the c# function, then it should use default ?
So you're saying that as null is valid for the string argument, it does not take the default value right ?

I learned something then thanks :)

Re: Optional parameters from X# to C#

Posted: Thu Jan 02, 2025 12:41 pm
by Chris
Hi Basile,

Yes, NULL is a valid value for strings in .Net, means "no value", same as NULL or NULL_OBJECT for a DBServer var means also no value/object assigned to it.

The default value in the parameter is used only when you do not pass anything for it.