0

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();
        }
    }
}
Community
  • 1
  • 1
Rahul Jha
  • 1,131
  • 1
  • 10
  • 25
  • I've answered, but it's not clear whether the problem is actually your understanding of reflection, or that you simply don't know what an expression such as `new[] { typeof(int) }` means - and that in itself doesn't have anything to do with reflection. – Jon Skeet Oct 05 '15 at 15:52

2 Answers2

2

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • So your answer means in Line X "new Type[0]" effectively null ! Is there any other equivalent code we could have used as parameter in Line Y ! – Rahul Jha Oct 05 '15 at 16:45
  • @RahulJha: No, a reference to an empty array is very different (in general) to a null reference. – Jon Skeet Oct 05 '15 at 16:54
0

The simplest overload of Type.GetConstructor still takes an array of types to indicate the parameters of the constructor you're trying to get.

The value Type[0] is an empty array, which indicates no parameters.

Jamiec
  • 133,658
  • 13
  • 134
  • 193