thanksalot
thanksalot

Reputation: 115

c# string to class from which I can call functions

on initialize a class by string variable in c#? I already found out how to create an class using a string

so what I already have is:

Type type = Type.GetType("project.start");
var class = Activator.CreateInstance(type);

what I want to do is call a function on this class for example:

class.foo();

is this possible? and if it is how?

Upvotes: 1

Views: 1425

Answers (5)

ryudice
ryudice

Reputation: 37406

var methodInfo = type.GetMethod("foo");
object result  = methodInfo.Invoke(class,null);

The second argument to the Invoke method are the method parameters.

Upvotes: 0

Ian Nelson
Ian Nelson

Reputation: 58753

If you can assume that the class implements an interface or base class that exposes a Foo method, then cast the class as appropriate.

public interface IFoo
{
   void Foo();
}

then in your calling code you can do:

var yourType = Type.GetType("project.start");
var yourObject = (IFoo)Activator.CreateInstance(yourType);

yourType.Foo();

Upvotes: 2

Austin Salonen
Austin Salonen

Reputation: 50235

Activator.CreateInstance returns a type of object. If you know the type at compile time, you can use the generic CreateInstance.

Type type = Type.GetType("project.start");
var class = Activator.CreateInstance<project.start>(type);

Upvotes: 0

Quintin Robinson
Quintin Robinson

Reputation: 82355

It is possible but you will have to use reflection or have class be cast as the proper type at runtime..

Reflection Example:

type.GetMethod("foo").Invoke(class, null);

Upvotes: 1

LukeH
LukeH

Reputation: 269498

Type yourType = Type.GetType("project.start");
object yourObject = Activator.CreateInstance(yourType);

object result = yourType.GetMethod("foo")
                        .Invoke(yourObject, null);

Upvotes: 4

Related Questions