patterncsharpMinor
Gathering tokens from ASP.NET routes
Viewed 0 times
routesgatheringnetfromtokensasp
Problem
This is one of the (many) utilitarian classes I have that I use with my ASP.NET sites.
The basis of this one is to make gathering certain tokens that I use periodically, to make URL's more friendly.
It's pretty simple, and should be quite obvious. I use it to make URL's a little more friendly. (
The basis of this one is to make gathering certain tokens that I use periodically, to make URL's more friendly.
It's pretty simple, and should be quite obvious. I use it to make URL's a little more friendly. (
/Id/SomeKey/SomeValue/OtherKey/OtherValue/) It returns Id and creates a dictionary for the remaining pairs of Key and Value.public class RouteUtilities
{
public static Dictionary GetRouteKeyValuePairs(RouteValueDictionary dataTokens, int startIndex)
{
Dictionary routeItems = new Dictionary();
List segments = GetRouteSegments(dataTokens);
for (int i = startIndex; i GetRouteSegments(RouteValueDictionary dataTokens) => (List)dataTokens["FriendlyUrlSegments"];
public static bool GetIdAndKeys(RouteValueDictionary dataTokens, out int id, out Dictionary keys)
{
if (dataTokens.Count > 0)
{
Dictionary routeItems = GetRouteKeyValuePairs(dataTokens, 1);
List routeSegments = GetRouteSegments(dataTokens);
if (routeSegments.Count > 0)
{
id = Convert.ToInt32(routeSegments[0]);
keys = GetRouteKeyValuePairs(dataTokens, 1);
return true;
}
}
id = 0;
keys = null;
return false;
}
}Solution
In
GetIdAndKeys(), you do the default initialization of the out variables just before the default return. I find it is usually better to initialize these variables at the top of the method because many methods will have multiple early return conditions, as well as a default return value. Doing the default initialization at the beginning of the method prevents needing to do it in multiple places, and aids in consistency if the specific method does not have this problem.public static bool GetIdAndKeys(RouteValueDictionary dataTokens, out int id, out Dictionary keys)
{
id = 0;
keys = null;
if (dataTokens.Count > 0)
{
// re-assign and return
}
return false; // use default values
}Code Snippets
public static bool GetIdAndKeys(RouteValueDictionary dataTokens, out int id, out Dictionary<string, string> keys)
{
id = 0;
keys = null;
if (dataTokens.Count > 0)
{
// re-assign and return
}
return false; // use default values
}Context
StackExchange Code Review Q#112063, answer score: 3
Revisions (0)
No revisions yet.