Table of contents
- 1 Accessing the dictionary directly
- 2 Using a Dictionary Adapter
Using Nullables
You can exploit the nullables support of .NET 2.0 to make your code more readble and maintainable.
Accessing the dictionary directly
Assuming we want to be able to access a session variable named "UserId", and that we need to make sure that the value exists before reading it. With direct access to the Session dictionary, the code would look something like that:
... if (Session["UserId"] != null) { int UserId = (int)Session["UserId"]; someService.DoImportantStuffOn(UserId); } ...
Using a Dictionary Adapter
Now let's do te same using the Dictionary Adapter.
First, we have to declare the interface. This time we'd use a nullable int.
public interface IUserIdAware { int UserId? { get; set; } }
Now we can use the adapter to get a cleaner access:
... IUserIdAware TypedSession = new DictionaryAdapterFactory().GetAdapter<IUserIdAware>(Session); if (TypedSession.UserId.HasValue) someService.DoImportantStuffOn(TypedSession.UserId.Value); ...