I was putting together an Excel add-in with some User Defined Functions (UDFs), using C#. Based on excelDNA documentation, I created a class that checks to see if OPTIONAL Excel arguments are present in a UDF. And if not, it assigns a default value.
I created a couple of simple test functions to see if the OPTIONAL class is working "correctly". They just add 100 to the Excel argument. (Excel screenshot attached below) Checks for double data types (and others) seem to be working, but INT data types aren't working. It seems to me like the "if (arg is Int)" isn't catching anything and I can't figure out why.
Stupid beginner question...Can anyone point out what I'm doing wrong? Thanks!
I created a couple of simple test functions to see if the OPTIONAL class is working "correctly". They just add 100 to the Excel argument. (Excel screenshot attached below) Checks for double data types (and others) seem to be working, but INT data types aren't working. It seems to me like the "if (arg is Int)" isn't catching anything and I can't figure out why.
Stupid beginner question...Can anyone point out what I'm doing wrong? Thanks!
C#:
public static class OptionalArg
// https://excel-dna.net/docs/guides-basic/optional-parameters-and-default-values/
// internal static class OptionalArg
{
// check to see if optional argument, if present, is an integer
internal static int Check(object arg, int defaultValue)
{
if (arg is int)
return (int)arg;
else if (arg is ExcelMissing)
return defaultValue;
else
throw new ArgumentException(); // Will return #VALUE to Excel
}
// check to see if optional argument, if present, is a double
internal static double Check(object arg, double defaultValue)
{
if (arg is double)
return (double)arg;
else if (arg is ExcelMissing)
return defaultValue;
else
throw new ArgumentException(); // Will return #VALUE to Excel
}
}
public class FuncString : XlCall
// public static class FuncString
// static classes are non-instantiable. Static classes cannot be inherited from another class.
{
// ==================== START of Function ====================
// Description for IntelliSense Tool Tip
[ExcelFunction(Description = "Function to test the optional argument (integer) class.")]
public static int C_TestInt(object intArg)
{
int addend = OptionalArg.Check(intArg, 1); // "1" is the default value
return 100 + addend;
}
// ==================== START of Function ====================
// Description for IntelliSense Tool Tip
[ExcelFunction(Description = "Function to test the optional argument (double) class.")]
public static double C_TestDbl(object dblArg)
{
double addend = OptionalArg.Check(dblArg, 1.5); // "1.5" is the default value
return 100 + addend;
}
}