-1

Why can't I do Class.GetMethod(string) but I can do this.GetType().GetMethod(string)?

I want to do the former because it seems like it would be a lot quicker since I already know what class I want to search in...

ovatsug25
  • 7,786
  • 7
  • 34
  • 48

3 Answers3

7

GetMethod is a method declared on the Type class... not on the class you're looking at. (In particular, that class could also have a GetMethod method, which would confuse things significantly...)

You can use

typeof(Class).GetMethod(...)

though, rather than getting the type of a specific instance - is that all you were looking for?

EDIT: Note that GetType(string) is only declared on Type and Assembly (and perhaps some other types). The normal Object.GetType() method doesn't have a string parameter.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • I was guessing that if I could give it something more specific (not a string) it would be faster...so yes, I guess that does help! – ovatsug25 Aug 12 '13 at 15:51
  • @ovatsug25: What do you mean by "give it something more specific"? Your requirements are very unclear here... the `Class.GetMethod(string)` that you say you want *is* still using a string... I thought you only wanted to get rid of using the call to `this.GetType(string)` - which wouldn't even compile, in fact. – Jon Skeet Aug 12 '13 at 15:52
2

Because the former is how you would call a static method on the class.

If you want to get the type of a class, just use typeof:

typeof(Class).GetMethod(someString);
Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
1

Well, you can do either:

typeof (MyClass).GetMethod("MyMethod");

or

MyClass myClass = new MyClass();
myClass.GetType().GetMethod("MyMethod");

Just to add - myClass.GetType().GetMethod("MyMethod") - Is resolved at runtime, where typeof(MyClass).GetMethod("MyMethod") at compile time.

Here is a bit more on it.

Community
  • 1
  • 1
Dimitar Dimitrov
  • 14,868
  • 8
  • 51
  • 79
  • I don't think your second example is equivalent to the first. The first example calls the `GetMethod` method of the `Type` class. The second example attempt to call the `GetMethod` on the `MyClass` type. If `MyClass` doesn't define a method called `GetMethod`, it will generate a compile error. Perhaps you meant your second example to be `myClass.GetType().GetMethod("MyMethod")`? – Chris Dunaway Aug 12 '13 at 15:56
  • @ChrisDunaway Nope, both will return null if the method is not found. Also did you see my edit (I acknowledge that there is a difference), is this what you mean ? – Dimitar Dimitrov Aug 12 '13 at 16:01
  • @ChrisDunaway yeah I had a typo that I did out of being in a hurry, fixed that. – Dimitar Dimitrov Aug 12 '13 at 16:01