1

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?

5 Answers 5

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

object result = yourType.GetMethod("foo")
                        .Invoke(yourObject, null);
Sign up to request clarification or add additional context in comments.

Comments

2

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();

Comments

1

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);

Comments

0

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);

Comments

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.