How to resolve a complex type as a string implicitly
Last Updated on Saturday, 26 February 2011 12:42
Written by Joseph
Thursday, 30 September 2010 05:00
Written by Joseph
Thursday, 30 September 2010 05:00
Along the same lines as resolving a complex type in a conditional, I also want to be able to take the same Authorization Result, and use it to broadcast a message to the system (or user), and tell them why couldn’t they be authorized.
An example of the behavior I’m looking for is something like this:
var authorizationResult = Is.CurrentUser.AuthorizedTo.DoSomething();
if (!authorizationResult)
throw new AuthorizationException(authorizationResult);
The Authorization Exception takes a String in it’s constructor, just like a typical Exception. It does not take an AuthorizationResult. So how am I able to just pass in an authorizationResult like that? Again, the implicit operator is all we need:
public class AuthorizationResult
{
public bool IList<reason> Reasons { get; set; }
public static implicit operator string(AuthorizationResult authorizationResult)
{
if (authorizationResult.With(x => x.Reasons) == null)
return false;
var result = new StringBuilder();
foreach (var reason in authorizationResult.Reasons)
{
result.AppendLine(reason.Message);
}
return result.ToString();
}
}
Now I can use AuthorizationResult implicitly as both a bool and a string.
Tags: authorization, linkedIn
This entry was posted on Thursday, September 30th, 2010 at 5:00 pm and is filed under Programming, Showcase.
You can follow any responses to this entry through the RSS 2.0 feed.
You can leave a response, or trackback from your own site.

Leave a Reply