Optional non-system type parameters

In C # 4.0, additional parameters are added, which I have been waiting for quite a while. However, it seems that since only system types can be const , I cannot use any class / struct that I created as an optional parameter.

Is there some way that allows me to use a more complex type as an optional parameter. Or is it one of the realities that you just need to live with?

+6
c # optional-parameters
source share
2 answers

The best I could come up with for reference types was:

 using System; public class Gizmo { public int Foo { set; get; } public double Bar { set; get; } public Gizmo(int f, double b) { Foo = f; Bar = b; } } class Demo { static void ShowGizmo(Gizmo g = null) { Gizmo gg = g ?? new Gizmo(12, 34.56); Console.WriteLine("Gizmo: Foo = {0}; Bar = {1}", gg.Foo, gg.Bar); } public static void Main() { ShowGizmo(); ShowGizmo(new Gizmo(7, 8.90)); } } 

You can use the same idea for structures by making the parameter null:

 public struct Whatsit { public int Foo { set; get; } public double Bar { set; get; } public Whatsit(int f, double b) : this() { Foo = f; Bar = b; } } static void ShowWhatsit(Whatsit? s = null) { Whatsit ss = s ?? new Whatsit(1, 2.3); Console.WriteLine("Whatsit: Foo = {0}; Bar = {1}", ss.Foo, ss.Bar); } 
+10
source share

You can use any type as an optional parameter:

 using System; class Bar { } class Program { static void Main() { foo(); } static void foo(Bar bar = null) { } } 

Ok, I'm re-reading your question, and I think I understand what you mean - you want to do something like this:

 static void foo(Bar bar = new Bar()) { } 

Unfortunately, this is unacceptable, since the default value of the parameter must be known at compile time so that the compiler can bake it in the assembly.

+6
source share

All Articles