0

I have some problems about this section in C# language.

So I'm trying to do something like revealing reflection of this class and it's methods.

class Car
{
    public string Name { get; set; }
    public int Shifts{ get; set; }


    public Car(string name, int shifts)
    {
        Name = name;
        Shifts = shifts;
    }

    public string GetCarInfo()
    {
        return "Car " + Name + " has number of shifts: " + Shifts;
    }

}

So I have this class Car, and this method GetCarInfo(), now, I'm trying to: Dynamically create instance of this class Car, and dynamically calling a method GetCarInfo(), I would like to show result in console, but I can't when I run it it shows build errors. The application break every time.

Edit

Errors

Community
  • 1
  • 1
xVenum.dll
  • 73
  • 5

1 Answers1

2

Here's a example

namespace ConsoltedeTEstes
  {
 class Program
 {
    static void Main(string[] args)
    {
        //Get the type of the car, be careful with the full name of class
        Type t = Type.GetType("ConsoltedeTEstes.Car");

        //Create a new object passing the parameters
        var dynamicCar = Activator.CreateInstance(t, "User", 2);

        //Get the method you want
        var method = ((object)dynamicCar).GetType().GetMethod("GetCarInfo");

        //Get the value of the method
        var returnOfMethod = method.Invoke(dynamicCar, new string[0]);

        Console.ReadKey();
    }
}

public class Car
{
    public string Name { get; set; }
    public int Shifts { get; set; }


    public Car(string name, int shifts)
    {
        Name = name;
        Shifts = shifts;
    }

    public string GetCarInfo()
    {
        return "Car " + Name + " has number of shifts: " + Shifts;
    }

}


}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459