Sitecore Quick Tip: Getting and Setting SafeDictionary

Sitecore’s SafeDictionary is used throughout Sitecore’s libraries and the purpose of it (as opposed to using Dictionary) is to allow dictionary[key] without exceptions, instead returning default(T).

To read values into a SafeDictionary from a Sitecore field that uses a query string internally (validator parameters, rendering parameters, name value field etc.) you can use:

var parameters = Sitecore.Web.WebUtil.ParseQueryString(item["Field Name"]);

Then of course you can modify the SafeDictionary:

if (!parameters.ContainsKey("foo"))
    parameters.Add("foo", "bar");

And writing the SafeDictionary back to the field:

item["Field Name"] = string.Join("&", parameters.Select(x => $"{System.Web.HttpUtility.UrlEncode(x.Key)}={System.Web.HttpUtility.UrlEncode(x.Value)}"));


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s