Handle optional parameterized method of VB.Net or COM in C#

Although optional parameters are actually a very good feature, C# does not support them. Now what about assemblies created in VB.Net with methods having optional parameter, how to call them from C# code? Since C# doesn’t support the concept of optional parameter, if you don’t supply required parameters while making a call to such methods, compiler will throw an error.

So how to handle this? There are many ways to address this issue:
1. If the required parameter is of any reference type such as String then you can use
System.Reflection.Missing.Value or  System.Text.Missing
While making call to such methods pass the above value as optional parameter.
2. Create a Wrapper class in VB.Net and overload the method with different available options. This assembly could be referenced by the original C# application.

Now the upcoming version of C# 4.0 is going to have a feature of Optional Parameter
C# 4.0 can both declare and consume optional parameters. Here’s a sample of a very simple method that declares a parameter as optional:

public static class OptionalDemoLib
{
public static void SayHello(string s = "Hello World!")
{
Console.WriteLine(s);
}
}

This means you can either call Do with one argument or without an argument, in which case the default value is used:

public static class OptionalDemo
{
public static void Main()
{
OptionalDemoLib.SayHello();
OptionalDemoLib.SayHello("Hello India!");
}
}

Advertisements

About Krishnaraj Barvathaya

I am Krishnaraj Barvathaya, a software developer from Bangalore and I primarily write on Microsoft Technologies and latest technical stuffs which interests me.

Posted on January 16, 2009, in .Net and tagged , , , , , , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: