alexpanter
alexpanter

Reputation: 1578

C# Create default value for class, e.g. through reflection

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#?

Upvotes: 0

Views: 286

Answers (2)

alexpanter
alexpanter

Reputation: 1578

[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.

Upvotes: 0

Innat3
Innat3

Reputation: 3576

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);
}

Upvotes: 1

Related Questions