Invoke

In this chapter you will learn:

  1. Call constructor
  2. Get/set property using invoke member
  3. Reflecting and Activating Types

Call constructor

using System;/*  j  a v  a2 s.c o m*/
using System.Text;
using System.Reflection;

class MainClass
{
    public static void Main ()
    {
        Type type = typeof(StringBuilder);

        Type[] argTypes = new Type[] { typeof(System.String), typeof(System.Int32) };

        ConstructorInfo cInfo = type.GetConstructor(argTypes);

        object[] argVals = new object[] { "Some string", 30 };

        // Create the object and cast it to StringBuilder.
        StringBuilder sb = (StringBuilder)cInfo.Invoke(argVals);

        Console.WriteLine(sb);
    }
}

The code above generates the following result.

Get/set property using invoke member

using System;//from   j a  v  a2 s .  c  o  m
using System.Reflection;
using System.Windows.Forms;

public class Class1
{
    static void Main(string[] args)
    {
        Type type = typeof(MyClass);
        object o = Activator.CreateInstance(type);

        type.InvokeMember("Text", BindingFlags.SetProperty | BindingFlags.Instance | BindingFlags.Public, null, o, new object[] { "Windows Developer Magazine" });
        string text = (string)type.InvokeMember("Text", BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.Public, null, o, new object[] { });
        Console.WriteLine(text);

    }
    private static void OnChanged(object sender, System.EventArgs e)
    {
        Console.WriteLine(((MyClass)sender).Text);
    }
}
public class MyClass
{
    private string text;

    public string Text
    {
        get { return text; }
        set
        {
            text = value;
            OnChanged();
        }
    }

    private void OnChanged()
    {
        if (Changed != null)
            Changed(this, System.EventArgs.Empty);
    }

    public event EventHandler Changed;
}

Reflecting and Activating Types

using System;/*from j  a  v  a  2  s . co m*/
using System.Reflection;

class Example
{
    static void Main()
    {
        Type t = typeof(String);

        MethodInfo substr = t.GetMethod("Substring", 
            new Type[] { typeof(int), typeof(int) });

        Object result = 
            substr.Invoke("Hello, World!", new Object[] { 7, 5 });
        Console.WriteLine("{0} returned \"{1}\".", substr, result);
    }
}

Next chapter...

What you will learn in the next chapter:

  1. Instantiating Types
  2. Instantiate generic types
Home » C# Tutorial » Reflection
Reflection
Type
Type properties
Field reflection
Field Type
Field Attributes
FieldHandle
Field value
Set Field value
delegate reflection
Event reflection
Indexer reflection
Properties Reflection
Method
Parameter
Invoke
Type Instantiating
interface reflection
Generic type reflection
Reflection on nested Types
Subtype
Array reflection
Assembly