Gino Gino - 2 months ago 6x
C# Question

Initialize dynamically the var filter

What I'm trying to achieve is to initialize the "filter" variable dynamically based on what my method gets.

  • Initializing it to null throws an error.

  • Leaving it empty throws error.

  • Setting it to a generic type throws an error

  • Setting it to a new
    also throws an error

This is my code:

var filter=null;

if (id != 0)
if (subID != 0)
//Get Specific Categories
filter = builder.Eq("", id) & builder.Eq("", subID);
//Get SubCategories
filter = builder.Eq("", id);
//Get Generic Categories
filter = new BsonDocument();

I've been searching but nobody seems to have my problem or I'm not able to find it.


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.