Gino
Gino

Reputation: 176

Initialize dynamically the var filter

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

This is my code:

var filter=null;

if (id != 0)
    if (subID != 0)
        //Get Specific Categories
        filter = builder.Eq("Categories.Sub.id", id) & builder.Eq("Categories.Sub.Custom.id", subID);
    else
        //Get SubCategories
        filter = builder.Eq("Categories.Sub.id", id);
else
    //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.

Upvotes: 1

Views: 962

Answers (2)

Rahul
Rahul

Reputation: 77906

With var it's an implicit type and you can initialize a implicit type variable to null since it can be both value type and reference type; and value type can't be assigned to null (unless otherwise it's made nullable explicitly).

Thus instead of saying var filter=null; you should explicitly specify the type

BsonDocument filter = null; 

Upvotes: 0

Kelson Ball
Kelson Ball

Reputation: 983

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.

Upvotes: 2

Related Questions