What I'm trying to achieve is to initialize the "filter" variable dynamically based on what my method gets.
if (id != 0)
if (subID != 0)
//Get Specific Categories
filter = builder.Eq("Categories.Sub.id", id) & builder.Eq("Categories.Sub.Custom.id", subID);
filter = builder.Eq("Categories.Sub.id", id);
//Get Generic Categories
filter = new BsonDocument();
Var is not a dynamic variable, it is a keyword for type inference. These are very different concepts. The key issue is that in your code snippet the compiler can not figure out what kind of variable you want your
var to be.
var myNumber = 3; // myNumber is inferred by the compiler to be of type int. int myNumber = 3; // this line is considered by the computer to be identical to the one above.
The inferred type of a var variable does not change.
var myVariable = 3; myVariable = "Hello"; // throws an error because myVariable is of type int
The type of dynamic variables can change.
dynamic myVariable = 3; myVariable = "Hello"; // does not throw an error.
The compiler must be able to determine the type of an object when a var variable is created;
var myVariable = null; // null can be anything, the compiler can not figure out what kind of variable you want. var myVariable = (BsonDocument)null; // by setting the variable to a null instance of a specific type the compiler can figure out what to set var to.