C# optional parameters? Is it possible to make a perl's hashref-like optional list?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Dear C# Gurus

I'd like to implement a function with several optional parameters, (all of them are boolean value)
In perl, you can write the function as
$obj->Func({'OutputXML'=>'on', 'OutputSQLScript'=>'on', 'OutputToFile'=>'off'})

Is there a way to implement a fuction with parameters easy to use and maintain like that? Does C# support default parameter

Your responses are highly appreciated

C# Newbie
 
C# doesn't support optionals, you'll need to write an overload
MagicGuru said:
Dear C# Gurus,

I'd like to implement a function with several optional parameters, (all of them are boolean value).
In perl, you can write the function as:
$obj->Func({'OutputXML'=>'on', 'OutputSQLScript'=>'on', 'OutputToFile'=>'off'});

Is there a way to implement a fuction with parameters easy to use and
maintain like that? Does C# support default parameter?
 
no. c# does not support that. with the example you give, you could probably use flag enum (basically a bitfield) to achieve the same result

[Flags] public enum Output { Xml = 1, SqlScript = 2, File = 4

your method would b

public void Func( Output output

// do stuff her


public void Func(

// since c# doesn't support optional paramete
// you have to use method overloadin
// this calls overloaded Func with default valu
// equivalent of Xml:ON, SqlScript:ON, File:OF
// but you'd have to call other combinations manuall
Func( Output.Xml | Output.SqlScript )


hope this helps

----- MagicGuru wrote: ----

Dear C# Gurus

I'd like to implement a function with several optional parameters, (all of them are boolean value)
In perl, you can write the function as
$obj->Func({'OutputXML'=>'on', 'OutputSQLScript'=>'on', 'OutputToFile'=>'off'})

Is there a way to implement a fuction with parameters easy to use and maintain like that? Does C# support default parameter

Your responses are highly appreciated

C# Newbie
 
You can use the params keyword in C#, and do something like this:

static void Main(string[] args)

{

bool[] choices ={true,false };

output(choices);

Console.ReadLine();

}


static void output(params bool[] choices)

{


bool OutputXml=false;

bool OutputSQLScript=false;

bool OutputToFile=false;

if( choices.Length >0 ) OutputXml=choices[0];

if(choices.Length >1 ) OutputSQLScript=choices[1];

if(choices.Length >2 ) OutputToFile=choices[2];

Console.WriteLine(OutputXml.ToString()
+OutputSQLScript.ToString()+OutputToFile.ToString());

}



HTH -

Peter
 
Back
Top