0

I have several classes that contain validation methods in them : ClientValidation, PaymentValidation, etc. The plan is to dynamically build a list of methods that I would use to validate a record. To do this I need to be able to get a list of the methods contained within each class. To do that I have written the following line:

var methods = typeof( ClientValidation ).GetMethods();

This works great if all my methods were under the ClientValidation class, but they are not. What I want to be able to do is be able to dynmically pass in the class name so the line could look more like:

var dynamicClassName = GetClassNameMethod();

var methods = typeof( dynamicClassName ).GetMethods();

Is this possible? How would I do this?

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
kurabdurbos
  • 267
  • 1
  • 14
  • Side note: for future question instead of variations of "searched alot" please add links to articles/questions you've found with one line description why particular solution did not work for you. – Alexei Levenkov Sep 30 '15 at 19:15

1 Answers1

1

You can do this:

var methods = Type.GetType(full_class_name).GetMethods();

Where full_class_name is the full class name (with the namespace). For example: "ConsoleApplication1.Class1".

If you want to use the class name without the namespace (e.g. "Class1"), you can search the assembly for such class like this:

var methods = Assembly.GetExecutingAssembly().GetTypes().First(x => x.Name == class_name).GetMethods();

Where class_name is the class name like "Class1".

Yacoub Massad
  • 27,509
  • 2
  • 36
  • 62
  • I could not make this work or any of the other methods and I just realized why - The methods are in a different assembly and not in the current one that is executing. When I used this in the right location it worked like a charm. This is why I had no luck with the other duplicates. Sorry for the duplicate. – kurabdurbos Sep 30 '15 at 19:36
  • If you know some class (e.g. `Class2`) in the other assembly, you can use `typeof(Class2).Assembly` to get that assembly. – Yacoub Massad Sep 30 '15 at 19:38