Check function existence in C#

Asked

Viewed 219 times

1

How can I verify if a function exists in C#? I think I have to use some kind of reflection, but I don’t know much about it. Is there any way to get the function’s list of arguments, if it exists?

For example:

public class ClasseA {

public bool Funcao1(string a, string b){       

    //Código da função
}

public bool Funcao2(string a, string b){
    //Código da função
}

public bool Funcao10(string a, string b) {
   //Código da função
}

public bool VerificaExistenciaFuncoes(){
{
       bool bTodasExistem = true;
       for(int i = 1; i<=10;i++){

         // Aqui quero fazer algo do tipo:
         // Se função não existe "Funcao" + i -> bTodasExistem = false;
      }              

    return bTodasExistem;

}

}
  • Check where? What for?

  • I’ll change the question to make it more specific

  • Why do this? All exist, is ready there, this use makes no sense. C# is not a dynamic language that the function may or may not exist. You’d need to show a case where that’s useful, in which case the VerificaExistenciaFuncoes() does nothing that is no longer known to the programmer.

  • So now you need to give us more information than you actually want so we can see what to do...

3 answers

2


I don’t see a point in doing that. As was said in the comments, C# is not a dynamic language that the function may or may not exist. However, I will answer anyway.

As you said in the question, you can use Reflection to check whether or not the method exists on the object. A simple example would be this:

using System;

public class Program
{
    public static void Main()
    {
        var classeA = new ClasseA();
        var existeFuncoes = VerificaExistenciaFuncoes(classeA, "Funcao");
        Console.WriteLine(existeFuncoes);

    }
    public static bool VerificaExistenciaFuncoes(object obj, string prefixMethod)
    {
        var type = obj.GetType();
        bool bTodasExistem = true;
        for (int i = 1; i <= 10; i++)
        {
            var function = type.GetMethod(prefixMethod + i);
            //estou percorrendo o laço todo, mas poderia retornar false de uma vez
            if (function == null)
                bTodasExistem = false;
        }

        return bTodasExistem;
    }
}


public class ClasseA
{

    public bool Funcao1(string a, string b)
    {
        return true;
    }

    public bool Funcao2(string a, string b)
    {
        return true;
    }

    public bool Funcao10(string a, string b)
    {
        return true;
    }
}

Note that I have separated the method VerificaExistenciaFuncoes() of classeA and put 2 parameters for it, obj and prefixmethod.

Obj is nothing more than the object you are checking whether the method exists or not.

prefixMethod is the prefix of the function you want to check. Since what will change in your example is only the number, I put this parameter to make it easier to explain.

Now, to check whether the method exists or not, just use the Type.Getmethod(), passing the name of the method you want to verify.

See working on Dotnetfiddle.

2

Here is an example of how to get the methods and their list of parameters:

using System;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace Teste
{
    public class Program
    {
        public static void Main(string[] args)
        {            
            Teste t = new Teste();
            //Pega todas as informações dos metodos a partir do tipo do objeto (classe), você pode informar através das flags um filtro (publico, privado)
            MethodInfo[] methodInfos = Type.GetType(t.GetType().ToString()) 
                           .GetMethods(BindingFlags.Public | BindingFlags.Instance);

            foreach (MethodInfo method in methodInfos)
            {
                //Mostra o nome do metodo
                System.Console.WriteLine(method.Name);
                //Pega todos os parametros do metodo
                foreach(ParameterInfo parameter in method.GetParameters())
                {
                    //Posição do parametro
                    int pos = parameter.Position;
                    //Nome do tipo do parametro (int, string)
                    string nameOfType = parameter.ParameterType.Name;
                    //Nome do parametro
                    string nameOfParam = parameter.Name;
                    System.Console.WriteLine(pos);
                    System.Console.WriteLine(nameOfType);
                    System.Console.WriteLine(nameOfParam);
                }
            }
        }
    }

    public class Teste
    {
        public void meuMetodo(string arg1, string arg2)
        {

        }

        public int meuMetodo2(int arg1, int arg2)
        {
            return 1;
        }
    }
}

References:

I hope I’ve helped.

0

There is, and it’s already answered in English here https://stackoverflow.com/questions/8499593/c-sharp-how-to-check-if-namespace-class-or-method-exists-in-c

More precise answer in English and translated:

You can resolve a Type from a string by using the Type.Gettype(String) >method. For example:

To solve a class from a String you can use the Type.Gettype(String)

Type myType = Type.GetType("MyNamespace.MyClass");

You can then use this Type instance to check if a method exists on the >type by Calling the Getmethod(String) method. For example:

From the class, it is possible to validate the existence of a function through the Getmethod(String) function. For example:

MethodInfo myMethod = myType.GetMethod("MyMethod");

Both Gettype and Getmethod Return null if no type or method was found for the Given name, so you can check if your type/method exist by checking if your method call returned null or not.

Both the Gettype and Getmethod function will return null case for the given String, there is no class or function respectively.

Finally, you can instantiate your type using >Activator.Createinstance(Type) For example:

Finally, from the data obtained, it is possible to instantiate an object of the class from the function Activator.Createinstance(Type)

object instance = Activator.CreateInstance(myType);

Regarding the second part of the question, to get the parameters, there is the Getparameters() function that belongs to class Methodinfo.:

ParameterInfo[] pars = myMethod.GetParameters(); foreach (ParameterInfo p in pars) { Console.WriteLine(p.ParameterType); }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.