Reputation: 709
I have created the class name cls1 and created method called GrantAccess().but the i am not able to access _entities.it's showing the below error "Error 1 An object reference is required for the non-static field, method, or property 'Path._entities".
public class cls1
{
private readonly DBEntities _entities;
public cls1 ()
{
if (_entities == null)
{
_entities = new DBEntities();
}
}
public static void GrantAccess()
{
if (Settings.DbLog == "1")
{
_entities.II_CCLog("Excuting the GrantAccess() Method");
}
}
}
The above method is called in some other class.
public void GetCConfig()
{
cls1.GrantAccess();
}
Upvotes: 3
Views: 1659
Reputation: 121
You are mixing static code with instance code. If you're working with objects, don't make your method GrantAccess static:
public void GrantAccess()
{
if (Settings.DbLog == "1")
{
_entities.II_CCLog("Excuting the GrantAccess() Method");
}
}
Then you'll have to create an instance of cls1:
public void GetCConfig()
{
var instance = new cls1();
cls1.GrantAccess();
}
You should also make cls1 disposable and call .Dispose() on _entities after you're finishied using it.
public class cls1 : IDisposable
{
...
public void Dispose()
{
_entities.Dispose();
}
Put the cls1 instance into a using block, like this:
public void GetCConfig()
{
using(var instance = new cls1())
{
cls1.GrantAccess();
}
}
Finally, the following line is not needed, because _entities will always be null at the beginning of the constructor.
if (_entities == null)
{
I'd suggest reading some basic documentation about object oriented programming with c#, for example: https://msdn.microsoft.com/en-us/library/dd460654.aspx
Upvotes: 1
Reputation: 35544
GrantAccess
is a static method while _entities
is not a static variable. So you need to make GrantAccess
a non-static method or you have to make _entities
a static variable.
Static methods and properties cannot access non-static fields and events in their containing type, and they cannot access an instance variable of any object unless it is explicitly passed in a method parameter.
Or create a new instance of DBEntities in the static GrantAccess method and perform your operation on this instance.
public static void GrantAccess()
{
if (Settings.DbLog == "1")
{
DBEntities entities = new DBEntities();
entities.II_CCLog("Excuting the GrantAccess() Method");
}
}
Upvotes: 1
Reputation: 556
first you have to create an object of cls1 in the class where you are calling the method of the cls1 class and then with from that object reference you will be able to call the method GrantAccess();
. You can create object by following way :-
variable_name = new class_name( );
Upvotes: 1