Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize var to null

Tags:

c#

linq

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?

like image 311
P.Brian.Mackey Avatar asked May 24 '11 14:05

P.Brian.Mackey


People also ask

How do you declare a variable as null?

var x = (T)null; Hope this helps.

Can we assign null to VAR?

var can only be used when a local variable is declared and initialized in the same statement; the variable cannot be initialized to null, or to a method group or an anonymous function.

Can we assign null to var in C#?

In C#, the compiler does not allow you to assign a null value to a variable.

Can var be null in Java?

The compiler can correctly infer that the type is the Null type (which can only hold null), but because declaring a variable of Null type is so obviously useless, it issues an error instead of doing what is obviously not what the user meant.


2 Answers

You can try this:

var firstModel=(dynamic) null; 
like image 136
kiyan r.z.h Avatar answered Oct 12 '22 10:10

kiyan r.z.h


You can use FirstOrDefault() instead.

firstModel = contextSelectResult.FirstOrDefault();

if(firstModel != null)
{
   ...
}
like image 34
Bala R Avatar answered Oct 12 '22 12:10

Bala R