Is there any advantige using delegates instead of methods? For example: public v
ID: 642277 • Letter: I
Question
Is there any advantige using delegates instead of methods? For example:
public void LoginAuthenticate(object sender, AuthenticateEventArgs e)
{
if (Membership.ValidateUser(lgUserLogin.UserName, lgUserLogin.Password))
{
Func<string, string> getDestinationPage = (userLogin) => { //definition };
e.Authenticated = true;
lgUserLogin.DestinationPageUrl = getDestinationPage(lgUserLogin.UserName);
}
else
{
Action<string> invalidLogin = (msg) =>
{
lgUserLogin.FailureText = string.IsNullOrWhiteSpace(msg) ? "Invalid login" : msg;
e.Authenticated = false;
};
MembershipUser user = Membership.GetUser(lgUserLogin.UserName);
if (user != null)
{
if (user.IsLockedOut)
{
invalidLogin("User has been blocked");
}
else if (!user.IsApproved)
{
invalidLogin("User is not activated");
}
else
{
invalidLogin(null);
}
}
else
{
invalidLogin(null);
}
}
}
If I getDestinationPage define as private string getDestinationPage(string login){...} and invalidLogin as private void invalidLogin(string msg){...}
does it gives any benefits?
Explanation / Answer
In your case it makes the code cleaner and more readable to use methods. There is no benefit in using delegates like this.
Your code would look like this:
private string getDestinationPage(string userLogin)
{
// definition
}
private void invalidLogin(string msg)
{
lgUserLogin.FailureText = string.IsNullOrWhiteSpace(msg)
? "Invalid login"
: msg;
}
public void LoginAuthenticate(object sender, AuthenticateEventArgs e)
{
if (Membership.ValidateUser(lgUserLogin.UserName, lgUserLogin.Password))
{
e.Authenticated = true;
lgUserLogin.DestinationPageUrl = getDestinationPage(lgUserLogin.
UserName);
}
else
{
e.Authenticated = false;
MembershipUser user = Membership.GetUser(lgUserLogin.UserName);
if (user != null)
{
if (user.IsLockedOut)
{
invalidLogin("User has been blocked");
}
else if (!user.IsApproved)
{
invalidLogin("User is not activated");
}
else
{
invalidLogin(null);
}
}
else
{
invalidLogin(null);
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.