-1

based on this post: Instantiate a class from its textual name

I am trying to access the method inside of instantiated object but it's still an object. We know that it must be casted before we can access the method. In my case, I can't do the cast because the class is dynamic. Is there any solution?

So far my code not to different from that post above. I just need to call the method after instantiated.

Thanks in advance

Community
  • 1
  • 1
andrefadila
  • 647
  • 2
  • 9
  • 36
  • 1
    Please show us your code. – Simon Whitehead Nov 06 '14 at 03:33
  • Not sure what do you mean... so you have class name at runtime, as a string, and once you get an instance of it, using reflection, you want to cast it (as in at compile time)? That doesn't make sense, if you already know the type you want to cast to at compile time. Please add more details on the actual problem you are trying to solve. – Vikas Gupta Nov 06 '14 at 03:37

2 Answers2

2

You have at least two options for dynamic invocation of methods when the usual type-safe methods aren't applicable:

dynamic o = GetSomeObject();

o.SomeMethod();

or:

object o = GetSomeObject();
MethodInfo mi = o.GetType().GetMethod("SomeMethod");

mi.Invoke(o);

Note that the former is simpler and benefits from some compiler and run-time support (including caching of the dynamic binding) that doesn't occur in the latter example.

Peter Duniho
  • 68,759
  • 7
  • 102
  • 136
0

have you tried implementing the object as an interface?

or you can also use the 'as' keyword

MyClass test = regularobject as MyClass;
Cody Jones
  • 424
  • 1
  • 5
  • 16
  • I think you have misunderstood the question. – Simon Whitehead Nov 06 '14 at 03:40
  • 1
    I don't know if anyone would clearly understand the question as is, but if I had to guess, suggestion about using interfaces seems like might be what s/he is looking for.. but it is indeed still hard to say without getting problem clarified. – Vikas Gupta Nov 06 '14 at 03:42
  • @SimonWhitehead: in Cody's defense, the question is not clear at all. It's entirely possible that while the code finds the type by name, it is dealing only with types that implement a specific interface. – Peter Duniho Nov 06 '14 at 03:43
  • I agree its not a well written question - hence why I didn't downvote this answer because of the slight vagueness to the question. My understanding of it though is as you answered @PeterDuniho. – Simon Whitehead Nov 06 '14 at 03:45