1

I'm trying to store some values in the Cache to use them later and I think that this is what I need https://msdn.microsoft.com/en-us/library/18c1wd61.aspx, but can't get it to work...

This is how I try to use it (added using System.Web) :

Cache["name"] = "my name";

And it says:

The name 'Cache' does not exist in the current context

What am I missing?

Chandan Kumar
  • 4,570
  • 4
  • 42
  • 62

1 Answers1

1

From Cache Class:

The instance of Cache that is accessed by the snippet below is a member of the Page object that this sample inherits.

Your code must be in a Page method. You have also another instance available on the HttpContext, again, described on the same link:

One instance of this class is created per application domain, and it remains valid as long as the application domain remains active. Information about an instance of this class is available through the Cache property of the HttpContext object or the Cache property of the Page object.

You have to consider that Cache["<somestring>"] it must be an instance, not the class, since a class cannot have a static index accessor. So any sample you see like that, it must be a an instance, likely a property named Cache of some object.

Community
  • 1
  • 1
Remus Rusanu
  • 288,378
  • 40
  • 442
  • 569
  • This means that I can't use the `Cache` method in a `Windows Forms` Application? – Laura Cîrstea Mar 10 '17 at 10:09
  • You can *instantiate* a `Cache` and use it. But, in a forms application, it begs the question *why*? A web page back end has to deal with HTTP request lifecycle, but a forms app it does not. An app can simply use a variable to 'cache' something. – Remus Rusanu Mar 10 '17 at 10:12
  • My scope is to store a variable and display it in an input field when the user opens the form – Laura Cîrstea Mar 10 '17 at 10:16
  • For Winforms apps there is [`System.Runtime.Caching`](https://msdn.microsoft.com/en-us/library/system.runtime.caching(v=vs.110).aspx) namespace you can use, with classes like `MemoryCache`, `ObjectCache`, `SqlChangeMonitor `, `FileChangeMonitor` and so on. – Remus Rusanu Mar 10 '17 at 10:17
  • Tried that too, but I still get the error `The type or namespace name 'Caching' does not exist in the namespace 'System.Runtime' (are you missing an assembly reference?)` – Laura Cîrstea Mar 10 '17 at 10:18
  • You want to persist something between application restart? Then use a [User scoped Setting](https://msdn.microsoft.com/en-us/library/aa730869(v=vs.80).aspx) and save it. – Remus Rusanu Mar 10 '17 at 10:18
  • "The output caching functionality and types in the System.Runtime.Caching namespace were introduced in .NET Framework 4." – Remus Rusanu Mar 10 '17 at 10:20
  • I think that the `User scope Setting` is what I need to use. Thank you! – Laura Cîrstea Mar 10 '17 at 10:22