I have an older VB6 app that has a function RunReturningVAR it is a db call that could return an int
, string
, double
..... but not a RecordSet
. It was built very generically so that it can be called by multiple other functions so we don't have multiple locations for DB calls.
what I currently have is attached.
Public Function RunReturningVar(ByVal vstrSql As String, _
Optional ByVal connval As Boolean = False, _
Optional ByVal copyID As Double = 0, _
Optional ByVal corpVal As Boolean = False, _
Optional ByVal vintConnectionTimeout As Integer = 30) As Variant
VB6 Variant
(Can't believe I've found that link!) translates c# dynamic
.
public dynamic RunReturningVar(
string vstrSql,
bool connval = false,
double copyID = 0,
bool corpVal = false,
int vintConnectionTimeout = 30)
{
// do your stuff here
}
It almost translates to object
, but Variant
is a data type specific for
late-binding, and it can hold reference types and value types - unlike c# object
that can hold value types only through boxing.
Please note that working with dynamic
means you bypass all the compile time type checks, which can result with run time errors you wouldn't normally expect from a c# program.
Perhaps you could do better with generics, but that would require you to specify the return type from the calling method:
public T RunReturningVar<T>(
string vstrSql,
bool connval = false,
double copyID = 0,
bool corpVal = false,
int vintConnectionTimeout = 30) where T : new()
{
// do your stuff here and return T
}
Also, For a public method in a public class, I would strongly suggest against using optional parameters in c#.
Use method overloading to specify default values.
The reason for that is the way optional parameters works in c#:
When a method with an optional parameter is being called, and the optional parameter is omitted, it's default value gets compiled into the method call.
So if you call to this method from another assembly, omitting some of the optional parameters - like this:
yourObjectReference.RunReturningVar(sql, true);
The c# compiler actually translate that to:
yourObjectReference.RunReturningVar(sql, true, 0, false, 30);
This means that if you ever want to change the default value of any of the parameters, other assemblies referencing this one should also be recompiled. Therefor, a better alternative is to use method overloading:
public dynamic RunReturningVar(
string vstrSql,
bool connval,
double copyID,
bool corpVal,
int vintConnectionTimeout)
{
// do your stuff here
}
public dynamic RunReturningVar(
string vstrSql,
bool connval,
double copyID,
bool corpVal
)
{
return RunReturningVar(vstrSql, connval, copyID, corpVal, 30);
}
public dynamic RunReturningVar(
string vstrSql,
bool connval,
double copyID,
)
{
return RunReturningVar(vstrSql, connval, copyID, false);
}
and so on.