Named / Optional parameters in C # 3.0?

Is there a way to add additional parameters to C # 3.0, as in C # 4.0? I have to have this feature, I just can't wait!

Edit:

If you know a workaround / hack to do this, send it as well. Thanks!

+2
source share
5 answers

You can use an anonymous type and reflection as a workaround to named parameters:

public void Foo<T>(T parameters) { var dict = typeof(T).GetProperties() .ToDictionary(p => p.Name, p => p.GetValue(parameters, null)); if (dict.ContainsKey("Message")) { Console.WriteLine(dict["Message"]); } } 

So now I can call Foo as follows:

 Foo(new { Message = "Hello World" }); 

... and he will write my message.

Basically, I extract all the properties from the anonymous type that was passed in and convert them to a dictionary of string and object (property name and its value).

+13
source share

Unfortunately not. For this you need the C # 4.0 compiler. If you need additional options on the .NET platform today, you can try VB.NET or F #.

+8
source share

Always method overload. :)

+8
source share

As Dustin said, additional parameters are added in C # 4.0. One type of crap way of modeling additional parameters would be to have an object [] (or a more strongly typed array) as the last argument.

+4
source share

You can also use variable arguments as parameter parameters. An example of how this works is string.Format ().

See here:

http://blogs.msdn.com/csharpfaq/archive/2004/05/13/131493.aspx

+2
source share

All Articles