Extension methods as strongly typed wrappers C# with Example



Extension methods as strongly typed wrappers C# with Example

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. 

0 Comment's

Comment Form

Submit Comment