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?
var x = (T)null; Hope this helps.
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.
In C#, the compiler does not allow you to assign a null value to a variable.
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.
You can try this:
var firstModel=(dynamic) null;
You can use FirstOrDefault()
instead.
firstModel = contextSelectResult.FirstOrDefault();
if(firstModel != null)
{
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With