Click here to Skip to main content
15,884,177 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I'm not able to use:

if (this.OpenConnection() == true) (I'm using public static bool for this line and using private bool for OpenConnection)

in my Class Module in visual studio using C# language. It says

"Keyword "this" is not valid in a static property, static method, or static field initializer"

OpenConnection itself is located in the same class module.
Posted
Updated 1-May-15 4:22am
v2

What is unclear in this error message? It could be unclear only if you don't understand what static means.

Please see my past answers:
Type casting in c#[^],
C# windows base this key word related and its uses in the application[^],
What makes static methods accessible?[^].

—SA
 
Share this answer
 
You cannot call this in a static method because this refers to the current class instance, and a static method is not associated with an instance.

There are two possible solutions; what's the best, depends on your application:

  1. Make OpenConnection static, and call it like a static method.
  2. Make the caller an instance method.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 1-May-15 11:19am    
Basically, it's correct (I voted 4), but it does not touch root of the problem: understanding what is "static". Decisions on what to make static and what instance should not be a free choice. In each case, it should be one and only one, correct decision.

Please see my answer.

—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900