1 year ago

#386629

test-img

Liran Izak

Running all methods with a specific name in a namespace

I'm trying to check if a method exists in a namespace and run it(as the question's name says). I've tried to use two other questions in this forum, but couldn't combine their answers because when I've tried to, it gave me the error: System.NullReferenceException: 'Object reference not set to an instance of an object.'. and this is my code:

        void GetMethodInNSN(string methodName, string namespacename)
        {
            string @namespace = namespacename;
            List<string> classes = new List<string>();
            string method = methodName;
            

            var q = from t in Assembly.GetExecutingAssembly().GetTypes()
                    where t.IsClass && t.Namespace == @namespace
                    select t;
            q.ToList().ForEach(t => classes.Add(t.Name));

            var myClassType = Type.GetType(String.Format("{0}.{1}", @namespace, classes));
            object instance = myClassType == null ? null : Activator.CreateInstance(myClassType); //Check if exists, instantiate if so.
            var myMethodExists = myClassType.GetMethod(method) != null;

            if (myMethodExists)
            {
                MethodInfo methoToRun = myClassType.GetMethod(method);
                methoToRun.Invoke(methoToRun, new object[] {});
            }
        }

Can I get help, please?

By the way please include the namespaces/assemblies that the code uses.

c#

methods

namespaces

0 Answers

Your Answer

Accepted video resources