On VB.NET I can do things like this to write out all the keys in the cache:
Dim oc As HttpContext = HttpContext.Current
For Each c As Object In oc.Cache
oc.Response.Write(c.Key.ToString())
Next
Although the .Key doesn't come up in Intellisense the code works just fine.
How do I do the same in c#?
HttpContext oc = HttpContext.Current;
foreach (object c in oc.Cache)
{
oc.Response.Write(c.key.ToString());
}
It doesn't like the .key. bit. I'm at a loss here. Any ideas how to access the key in this way?
Almost right - it's a capital K
for Key
, not lower case. C# is case sensitive.
Additionally, object
doesn't have a Key
member. In C# you can use implicit type inference with the var
keyword as well. This will work if the underlying inferred type has a Key
member:
HttpContext oc = HttpContext.Current;
foreach (var c in oc.Cache)
{
oc.Response.Write(c.Key.ToString());
}
In this case, Cache
doesn't have a Key
member, so you need to dig deeper, using the IDictionaryEnumerator
returned by the GetEnumerator
method of Cache
:
HttpContext oc = HttpContext.Current;
IDictionaryEnumerator en = oc.Cache.GetEnumerator();
while(en.MoveNext())
{
oc.Response.Write(en.Key.ToString());
}
Below code snap is working fine:
HttpContext oc = HttpContext.Current;
foreach (var c in oc.Cache)
{
oc.Response.Write(((DictionaryEntry)c).Key.ToString());
}
Thanks for your time
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With