Extension methods as strongly typed wrappers

suggest change

Extension methods can be used for writing strongly typed wrappers for dictionary-like objects. For example a cache, HttpContext.Items at cetera…

public static class CacheExtensions
{
    public static void SetUserInfo(this Cache cache, UserInfo data) => 
        cache["UserInfo"] = data;

    public static UserInfo GetUserInfo(this Cache cache) => 
        cache["UserInfo"] as UserInfo;
}

This approach removes the need of using string literals as keys all over the codebase as well as the need of casting to the required type during the read operation. Overall it creates a more secure, strongly typed way of interacting with such loosely typed objects as Dictionaries.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents