Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object reference required for non-static field, method, or property

Tags:

c#

I want to use the Caching.Cache(...) method, like so:

Cache.Insert("Interview Questions", datatable, sqlcachedep)

or

System.Web.Caching.Cache.Insert("Reading List", datatable, sqlcachedep);

There is no problem with the variables, but I get this error message in either case:

Error 1 - An object reference is required for the non-static field, method, or property 'System.Web.Caching.Cache.Insert(string, object, System.Web.Caching.CacheDependency)'

How can I fix this?

Thanks

like image 422
GurdeepS Avatar asked Aug 19 '09 21:08

GurdeepS


People also ask

How do you fix an object reference is required for the non static field method or property in C#?

To correct this error, either (i) declare a variable of type program and then call the method or (2) add 'static' to the declaration of method pt().

How do I fix NullReferenceException object reference not set to an instance of an object?

The best way to avoid the "NullReferenceException: Object reference not set to an instance of an object” error is to check the values of all variables while coding. You can also use a simple if-else statement to check for null values, such as if (numbers!= null) to avoid this exception.

How can use static method in non static method in C#?

We can call non-static method from static method by creating instance of class belongs to method, eg) main() method is also static method and we can call non-static method from main() method . Even private methods can be called from static methods with class instance.

What is object reference not set to an instance of an object in C#?

The error means that your code is trying to access/reference an object that is a null valued object that is not there in memory.


2 Answers

It's saying the correct thing. You should try something like:

HttpContext.Current.Cache.Insert(...);

Cache.Insert is a not a static method (static methods are indicated by an "S" near the method icon in the documentation.) You need an instance to call the Insert method on. HttpContext.Current.Cache returns the Cache object associated with the current application.

like image 62
mmx Avatar answered Sep 21 '22 18:09

mmx


You need to do

Page.Cache.Insert()

(I'm assuming you're talking ASP.Net). You're calling on Cache as the class, not as the instance of it.

like image 29
womp Avatar answered Sep 22 '22 18:09

womp