Im learning C#. There is a question in a book (Exam Ref 70-483) which makes little sence to me, because I can't find any examples of it anywhere. I understand it in terms of eliminating the wrong answers and the right answer must be there.
A. Make the method public.
B. Use an event so outside users can be notified when the method is executed.
C. Use a method that returns a delegate to authorized callers.
D. Declare the private method as a lambda.
Correct answer 'C': "The method can see whether the caller is authorized and then return a delegate to the private method that can be invoked at will."
What is an example of this? What do they mean by authorized caller? There is no mention of authorized caller in the book. The only thing I could find about delegate and method authorization was about WCF and authorization, but that is for sure out of scope here. Well. I hope someone could shed some light on this! There are so many tough questions like this... well if not tough questions, difficult to understand answers.
Here's an example of how answer C can be implemented.
class Conspirator
{
private void SecretMethod()
{
Console.WriteLine("Secret exposed!");
}
public Action GetSecretMethod(long authorizationKey)
{
if (authorizationKey == 63278823982)
{
return this.SecretMethod;
}
return null;
}
}
As you see, SecretMethod
is private. GetSecretMethod
returns a delegate containing a reference to the private method, but only if the authorizationKey
passed is correct. Of course, this is a very basic form of "authorization" and in real life you would have some other mechanism of authorization.
You use this class in the following way:
void Main()
{
var conspirator = new Conspirator();
var secretPrinter = conspirator.GetSecretMethod(63278823982);
secretPrinter();
// Prints "Secret exposed!"
}