Reputation: 354
I get the error "The name _client does not exist in the current context." Same for "database" variable.
namespace MongoDB_Test
{
class Program
{
protected static IMongoClient _client;
protected static IMongoDatabase _database;
_client = new MongoClient(); // error here
_database = _client.GetDatabase("test"); // same error but for _database variable
}
}
I get no error with the below code:
namespace MongoDB_Test
{
class Program
{
protected static IMongoClient _client = new MongoClient();
protected static IMongoDatabase _database = _client.GetDatabase("test");
}
}
Why do I get the error for the first block of code?
Upvotes: 3
Views: 225
Reputation: 15794
You're missing the static constructor. Try this:
namespace MongoDB_Test
{
class Program
{
protected static IMongoClient _client;
protected static IMongoDatabase _database;
static Program()
{
_client = new MongoClient();
_database = _client.GetDatabase("test");
}
}
}
Basically this:
protected static IMongoClient _client = new MongoClient();
protected static IMongoDatabase _database = _client.GetDatabase("test");
Could be considered the functional equivalent of this:
static Program()
{
_client = new MongoClient();
_database = _client.GetDatabase("test");
}
That being said, field initialization and constructors do not execute at the same time - there is a sequence of events that occur, which you could look up if interested in the MSDN site.
Upvotes: 2
Reputation: 218828
You can't write code outside of a method unless it's a basic declaration/initialization line. Imperative code statements don't really make sense outside the scope of a method. Which is why your second example works.
You can, however, write a static constructor:
class Program
{
protected static IMongoClient _client;
protected static IMongoDatabase _database;
static Program()
{
_client = new MongoClient();
_database = _client.GetDatabase("test");
}
}
Keep in mind that field initializers (static or instance) and constructors (static or instance) and methods are all executed at very different times during the construction of an object. If the code relies on timing, you're going to want to make sure you initialize when you need to.
Upvotes: 11
Reputation: 34884
Move this:
_client = new MongoClient();
_database = _client.GetDatabase("test");
to a method, in this case it's static Main()
There's no error here:
protected static IMongoClient _client = new MongoClient();
because new MongoClient()
doesn't get executed, instead it implicitly gets copied to the static constructor which is a method and where it executes -- inside a method.
The bottom line is, you can execute code in methods only.
Upvotes: 2