I am writing a class that should ideally have multiple methods of the same signature. Is there a way to force the class to check its methods if all of them follow the same signature?
It would be ideal if the check could be done at compile-time/during build
If you assume the signature to be int <methodName>(string, int, char)
public class Conditions {
// no error
int MethodA(string a, int b, char c)
{
return 0;
}
// no error
int MethodB(string a, int b, char c)
{
return 1;
}
// should throw error because return type does not match signature
string MethodC(string a, int b, char c)
{
return "Should throw an error for this function";
}
}
}
It's sort of cheating, but if you require the developer to register their methods, you can force a compile time error by requiring the method to match a delegate.
This is essentially how event handlers and callbacks work.
namespace Framework
{
public delegate int MyApiSignature(int a, string b, char c);
public class Core
{
static public void RegisterMethod(MyApiSignature method)
{
//Doesn't even have to actually do anything
}
}
}
namespace Custom
{
using Framework;
class Foo
{
public Foo()
{
Core.RegisterMethod(MethodA); //Works
Core.RegisterMethod(MethodB); //Compile-time error
}
public int MethodA(int a, string b, char c)
{
return 0;
}
public int MethodB(int a, string b, byte c)
{
return 0;
}
}
}
You could make a unit test:
[TestMethod]
public void Conditions_MethodsHaveCorrectSignature()
{
var whitelist = new List<string> { "Finalize", "MemberwiseClone" };
var t = typeof(Conditions);
var m = t.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance);
foreach (var item in m.Where(x => !whitelist.Contains(x.Name)))
{
Assert.AreEqual(typeof(int), item.ReturnType);
CollectionAssert.AreEquivalent(new List<Type> { typeof(string), typeof(int), typeof(char) },
item.GetParameters().Select(x => x.ParameterType).ToList());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With