0

Let's say I have a class A:

public class A 
{
    private int value;
    public A() => value = 0;
    public A(int value) => this.value = value;
}

And I have some method, with a parameter list where some are defaulted:

public void SomeMethod(int i, float f, string s = "", A a = null)

Now is there some way, e.g. through reflection, to be more smart about this parameter list? I would like to be able to do something like the following, so I don't need to check for null everywhere:

public void SomeMethod(int i, float f, string s = "", A a = Default) // should use the empty constructor!

Is this possible with C#?

4
  • 1
    stackoverflow.com/questions/10727395/… Commented Sep 23, 2019 at 13:52
  • The closest thing to a default in c# is the default operator which would still be null in case of a reference type. Why can't you allow for a null and do the check once in the method's implementation? Commented Sep 23, 2019 at 13:54
  • Is that Method "Client-Facing"? If so, you need to validate parameters anyway. If it is actually OK to pass null , then you could use overloading as in Innat3's answer or use the Null-Object Pattern or just do var localA = a ?? new A(); Commented Sep 23, 2019 at 14:16
  • @LennartStoop Because I have a similar pattern many places in the code base, and having 0 as default int parameter is way better than having null for a class reference. Commented Sep 24, 2019 at 8:19

2 Answers 2

1

You could use method overloading

public void SomeMethod(A a, int i, float f, string s = "") { }

public void SomeMethod(int i, float f, string s = "")
{
    SomeMethod(new A(), i, f, s);
}
Sign up to request clarification or add additional context in comments.

Comments

0

[CONCLUSION]

It is not possible in C#. The default operator returns null for all reference types, and for value types it initializes all data fields using default operator. So in my case, I can actually omit this problem using a struct instead of a class:

public struct A 
{
    private int value;
    public A(int value) => this.value = value;
}

public void SomeMethod(int i, float f, string s = "", A a = default)

And then the input value will be a : A{value = 0}.

A general solution for using a class does not exist in C#, since default values are required to be determinable by compile time and must thus be constant expressions. Only valid constant expressions in C# are primitives, value types, and strings.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.