Mike Taulty's Blog
Bits and Bytes from Microsoft UK
I'm Missing My Default Parameter Values

Blogs

Mike Taulty's Blog

Elsewhere

I miss default parameter values from C++. In C# if I have some method Foo;

  static void Foo(int intValue, float floatValue, string stringValue)
  {
  }

and there's the possibility that all the parameters can be "optional" then I end up writing something like;

  static void Foo()
  {
    Foo(0, 0.0f, null);
  }
  static void Foo(int intValue)
  {
    Foo(intValue, 0.0f, null);
  }
  static void Foo(int intValue, float floatValue)
  {
    Foo(intValue, floatValue, null);
  }
  static void Foo(int intValue, float floatValue, string stringValue)
  {
  }

which is a lot of code when I really just want to say;

  static void Foo(int intValue = 0, float floatValue = 0.0f, string stringValue = null)
  {
  }

and my C++ compiler would have been happy with that but my C# compiler isn't going to be. Pity as I think that the single function definition is a lot nicer than the multiple function definitions. With object initialisation in C# V3.0 you almost feel like writing;

public class ArgType
{
  public int intValue = 0;
  public float floatValue = 0;
  public string stringValue = null;
}
class Program
{
  static void Main(string[] args)
  {
    Foo(new ArgType() { intValue = 10 });
  }
  static void Foo(ArgType arg)
  {
  }
}

but then two wrongs are never going to make a right :-)


Posted Mon, Aug 18 2008 6:46 AM by mtaulty
Filed under: ,

Comments

Reflective Perspective - Chris Alcock » The Morning Brew #161 wrote Reflective Perspective - Chris Alcock » The Morning Brew #161
on Tue, Aug 19 2008 1:08 AM