Иво Недев Иво Недев - 1 month ago 7
ASP.NET (C#) Question

Is it possible to have a Function that takes any number of variables of any type?

I have a simple function that takes a string and sends an email to me with that string (the function is used when debugging a live site)

public void errEmailV1(string strVars)
{
sendEmail("me@email","emailSubject",strVars);
}


Naturally to cal the function and send over multiple variables I'd:

Functions funcs = new Functions();
funcs.errEmailV1(someVariableThatisAString+", "+someIntVariable.ToString() +"...");


I later evolved my function to be able to call it faster

Functions funcs = new Functions();
funcs.errEmailV2(someVariableThatisAString,someIntVariable.ToString());

public void errEmailV2(params String[] paths)
{
string strVars="";
//a rather simplified version of the loop:
for (int i = 0; i < paths.Length; i++)
{
strVars+= paths[i];
}
sendEmail("me@email","emailSubject",strVars);
}


I doubt it is, but is it possible for my V3 to take any number of strings, ints and booleans (I rarely if ever send any other types) instead of having to always add
ToString()
?

Answer

What about using params object[] and String.Join:

Functions funcs = new Functions();
funcs.errEmailV2(someVariableThatisAString, someIntVariable);

public void errEmailV2(params object[] paths)
{
    string strVars= String.Join(", ", paths.Select(x => x.ToString());
    sendEmail("me@email","emailSubject",strVars);  
}