Here:
defaultCon
binds itself to Dog()
Constructor
legCon
binds itself to Dog(int legs)
Constructor
Why do we specify
new Type[0]
in Line X even though there are no parameters in Default Constructor
(new[] { typeof(int) })
in Line Y ! Curly braces inside argument/parameter field.Similar problem in Line Z.
I searched on StackOverflow - this answer came close but doesn't answer my question. Here is my code:
namespace Coding
{
internal class Dog
{
public int NumberOfLegs { get; set; }
public Dog()
{
NumberOfLegs = 4;
}
public Dog(int legs)
{
NumberOfLegs = legs;
}
}
public class Class1
{
static void Main(string[] args)
{
/*line X*/ var defaultCon = typeof(Dog).GetConstructor(new Type[0]); // Get Default Constructor without any params
/*line Y*/ var legCon = typeof(Dog).GetConstructor(new[] { typeof(int) });//get constructor with param int
var defaultDog = defaultCon.Invoke(null) as Dog;//invoke defaultCon for a Dog Object
/*Line Z*/ var legDog = legCon.Invoke(new object[] { 5 });//invoke legCon for a Dog object(Sets number of legs as 5) as Dog
Console.Read();
}
}
}
Why do we specify "new Type[0]" in Line X even though there are no parameters in Default Constructor
To say that there are no parameters - so the array of parameter types is empty.
Why do we specify "(new[] { typeof(int) })" in Line Y! Curly braces inside argument/parameter field.
To create an array or parameter types with a single element - the type corresponding to int
.
Similar problem in Line Z.
Same answer, except this time you're creating an array of arguments, instead of parameter types.
See more on this question at Stackoverflow