Delegates, a main question when it comes to C# interviews. When I faced the internship interview at IFS last October I was asked a question “What is a delegate” I said “It is a way to achieve thread safety”, actually I used delegates in my Imagine cup project in 2013 but when I faced that interviews, I really had a good clear concept of it. I said its thread safety because the reference material I read the day before the interview had many points on Delegates but due to my bad memory I could remember only that point even in that Imagine cup scenario really I used Delegate to avoid some code execution complexities.
Then the interviewer asked me ‘What do you mean by thread safety” so I explained it. Then again he asked me “OK, now how will you explain delegates to a newbie using the points you said”.. this is the moment I had a
In simple words, delegates are the callback functions in C#. (I really forgot this point that time)
So this JS pseudo code will explain what a callback function is,
If you can’t read that simple code, sorry this is not for you actually. So just close this browser tab.
Let me explain this,
delegate int CalcFunc(int a, int b); declare a delegate
CalcFunc that accepts two
int parameters and return another
int type variable.
CalcFunc someCalcFunc = new CalcFunc(SumFunc); instantiate the delegate
CalcFunk that calls a method we defined in Line 19, that is
SumFunc which SHOULD return the same return type and the same parameter types of the delegate
Console.WriteLine(someCalcFunc(5,6).ToString()); I just perform some operations with the delegate instance
Line 10, I change the reference of the
someCalcFunc delegate to another same return type method
ProdFunc, I don’t really need to make another instance of this delegate
CalcFunc for this purpose, simply
someCalcFunc = ProdFunc; works well.
and later I just perform some other operations.
I hope you will be able to catch it. Happy coding 🙂