Default Parameter Value ?

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

Guest

I there a way to provide a default value for a parameter in a method?

E.g.

private void somemethod(string whatever, string whatever2 = "someval")
 
Hi,
you cannot have optional parameters in C#, instead you can use method
overloading i.e.

private void SomeMethod(string whatever)
{
SomeMethod(whatever, "someval");
}

private void SomeMethod(string whatever, string whatever2)
{
//implement
}


Mark.
 
Thanks Mark.

Another quick question. I am calling methods from a COM object. These
methods contain optional parameters... in VB.NET I do not have to supply
values at all, just have to leave them blank. E.g.
SomeMethod("blah","blah",,,) or simply SomeMethod("blah","blah") . however,
in C# I receive a "no overload for method" error during compile. Why is it
in VB.NET I do not have to supply values but I must in C#? Is there a work
around?

Thanks a lot.
 
Hi,

In C# you must supply all parameters, including the COM-optional ones, so
Type.Missing is commonly used in cases like yours.

You may want to create a class that encapsulates the required functionality
of the COM object to provide a more .NET-centric wrapper for callers. You
can use Mark's method overloading suggestion to provide optional arguments
in C#. Although, many legacy COM classes provide an extraordinary number of
optional parameters (as in Office automation, for example) - too many to
create overloads for each possibility. In those cases it's important to
only wrap the functionality that you'll need.
 
If it goes in VB.Net with nothing (not the keyword) than it goes most
probably in C# with null, null, null, etc.

Cor
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top