I have a simple question about constructors in C#. Will these two code snippets behave the same way?
Code snippet #1:
public class foo
{
public foo(string a = null, string b = null)
{
// do testing on parameters
}
}
Code snippet #2:
public class foo
{
public foo()
{
}
public foo(string a)
{
}
public foo(string a, string b)
{
}
}
EDIT: And if I add this to the code snippet #1? It may look a really bad idea, but I'm working on refactoring a legacy code, so I'm afraid if I do sth that will cause damage to other piece of that uses that class.
public class foo
{
public foo(string a = null, string b = null)
{
if (a == null && b == null)
{
// do sth
}else if (a != null && b == null)
{
// do sth
}
if (a != null && b != null)
{
// do sth
}
else
{
}
}
}
The answer is no, the two are not going to behave the same.
The first snippet does not let your constructor decide if it has been called with a default parameter for a
and/or b
, or the caller has intentionally passed null
. In other words, passing null
s intentionally becomes allowed, because you cannot implement a meaningful null
check.
Another aspect in which these two code snippets would definitely differ - using constructors through a reflection:
No. Try using named arguments. The overload version will not compile. Because a
hasn't been given a value in the latter case.
var test = new foo1(b: "nope");
var test2 = new foo2(b: "nope");//CS7036 : There is no argument given that corresponds to the required formal parameter of
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With