Question

I'm trying to convert come vb.net code into C# but came across optional in one of the functions.

Private Function doOpenConnection(ByRef cn As OleDb.OleDbConnection, ByRef cmd As OleDb.OleDbCommand, ByVal sConnString As String, Optional ByVal sUSP As String = "") As Boolean

It seems like instead of using overloading, VB.Net has an option to create it into one method/function. Does C# have a similar equilvalent or do I have to create a method for each possbility?

Was it helpful?

Solution

C# has an equivalent as of C# 4:

private bool doOpenConnection(ref OleDb.OleDbConnection cn,
                              ref OleDb.OleDbCommand cmd,
                              string sConnString,
                              string sUSP = "")

Note that you probably don't need ref for the first two parameters here - it's important that you understand how parameter passing works in C#.

C# 4 has both named arguments and optional parameters. See MSDN for more information. Note that there are various restrictions, in that optional parameters have to come before required ones (aside from parameter arrays), and the default value has to be a constant (or you can use the default(...) operator).

OTHER TIPS

You can have optional parameters in C#.

From the MSDN:

Each optional parameter has a default value as part of its definition. If no argument is sent for that parameter, the default value is used. A default value must be one of the following types of expressions:

  • a constant expression;

  • an expression of the form new ValType(), where ValType is a value type, such as an enum or a struct;

  • an expression of the form default(ValType), where ValType is a value type.

Optional parameters are defined at the end of the parameter list, after any required parameters. If the caller provides an argument for any one of a succession of optional parameters, it must provide arguments for all preceding optional parameters. Comma-separated gaps in the argument list are not supported. For example, in the following code, instance method ExampleMethod is defined with one required and two optional parameters.

    public void ExampleMethod(int required, string optionalstr = "default string",
        int optionalint = 10)
    {
        Console.WriteLine("{0}: {1}, {2}, and {3}.", _name, required, optionalstr,
            optionalint);
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top