P.Brian.Mackey
P.Brian.Mackey

Reputation: 44285

Initialize var to null

I have seen how to initialize var to null. This does not help in my situation. I have

string nuller = null;
var firstModel = nuller;
if(contextSelectResult.Count() > 0)
    firstModel = contextSelectResult.First();

I get error

Cannot implicitly convert type 'SomeNamespace.Model.tableName' to 'string'.

I am trying to avoid try/catching InvalidOperation for First() when no first exists as its expensive. So, how can I get past the scope issue here?

Upvotes: 8

Views: 38277

Answers (7)

joao pais
joao pais

Reputation: 21

Please Try this option:

var var_name = (dynamic)null; 

or

var var_name = (Type*)null;

Type* : eg --> string, var, int

Upvotes: 2

gilix
gilix

Reputation: 545

You can use the generic for this case also

public static dynamic GetTheListOfDevicesDependOnDB(int projectID)
{
    List<Devices_Settings> ListDevices_Settings = new List<Devices_Settings>();
    var db = new First_DataContext();
    var devices = (dynamic) null;
    switch (projectID)
    {
        case (int)enmProjectType.First:
            db = new First_DataContext();
            devices = db.Device_Fisrt.ToList();   
            break;
        case (int)enmProjectType.Second:
             var db1 = new Second_DataContext();
             devices = db1.Device_Second.ToList();
            break;

        default:
            break;
    }

    foreach (var item in devices)
    {
       //TODO
    }

    return ListDevices_Settings;

}

Upvotes: 0

kiyan r.z.h
kiyan r.z.h

Reputation: 301

You can try this:

var firstModel=(dynamic) null; 

Upvotes: 26

canon
canon

Reputation: 41685

If there is no First it'll be a null for reference types:

var firstModel = contextSelectResult.FirstOrDefault();

Upvotes: 1

Dennis Traub
Dennis Traub

Reputation: 51644

Try FirstOrDefault instead. It returns nullby default if there is no item.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1501656

Simply use FirstOrDefault() instead. The whole point of FirstOrDefault is to return the first element of the sequence if it exists, or the default value of the element type (i.e. null for all reference types) otherwise.

Note that in other cases where you wish to check for the existence of any elements, using Any() can sometimes be more efficient than Count() > 0 - it depends on the exact context, but IMO it's a simpler way of expressing what you're looking for anyway.

Upvotes: 6

Bala R
Bala R

Reputation: 108957

You can use FirstOrDefault() instead.

firstModel = contextSelectResult.FirstOrDefault();

if(firstModel != null)
{
   ...
}

Upvotes: 7

Related Questions