I was experimenting with the the Type.GetMethod method the other day when I ran into a problem.
My program is a Windows application. There is one textbox in the form used for output and there are only these two blocks of code in the Form1_Load method:
MethodInfo info2 = typeof(IEnumerable<int>).GetMethod("GetEnumerator");
textBox1.Text += info2.ToString();
MethodInfo info1 = typeof(IEnumerator<int>).GetMethod("MoveNext");
textBox1.Text += info1.ToString();
The first GetMethod returned the correct information, but the second one returned nothing.
So I went one step further and included a try/catch statement in the code:
try
{
MethodInfo info2 = typeof(IEnumerable<int>).GetMethod("GetEnumerator");
textBox1.Text += info2.ToString();
MethodInfo info1 = typeof(IEnumerator<int>).GetMethod("MoveNext");
textBox1.Text += info1.ToString();
}
catch (Exception v)
{
textBox1.Text += v.Message;
}
The second GetMethod now gives me the error:
Object reference not set to an instance of an object.
I am confused. Neither method is static and neither takes any parameter. Why does MoveNext return the error while GetEnumerator doesn’t?
It is because the interface
IEnumerator<T>does not have a definition forMoveNext, that is in the interfaceIEnumerator.Example:
This will work fine,
You can loop though the Interfaces assigned to
IEnumerator<T>and findMoveNext