Click here to Skip to main content
15,886,026 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am sorry for this simple question! How to initilize a var that is going to be used for storing query result (db.query(...) or db.querysingle(...))?
C#
var queryResult;

This code will cause error because the var is not initilized. And when I give it null value I get this error:
Cannot assign null to an implicitly-typed local variable
Posted
Comments
Sandeep Mewara 28-Dec-12 9:24am    
Query result is what format - String? Datatable? What?
cs101000 28-Dec-12 10:27am    
queryResult is a single row returned by db.querysingle(...) or a set of rows returned by db.query(...) where db is a webmatrix DataBase. And this var is going to be fetched for getting its columns (and rows if any) like what people do in webmatrix. I just wana initilize it with a dummy value and then use it later when executing a query.

It depends on the query type.
If you use the Database.Query method, you can initialize the variable as
IEnumerable<dynamic> queryResult = null;


Otherwise, if you use the Database.QuerySingle method, the best way is
dynamic queryResult = null;
 
Share this answer
 
Var is an implicit type. So, you will have to assign it value where you declare it. It aliases any type in the C# programming language. The aliased type is determined by the C# compiler. You can not assign null to it.
 
Share this answer
 
Comments
cs101000 28-Dec-12 10:29am    
I know that. So I wana initilize it with something else just to prevent the error "Implicitly-typed local variables must be initialized"
Zafar Sultan 28-Dec-12 10:36am    
I don't know why there is a desperate need to declare it before using? Maybe you have some sort of scenario. But if you have to, then declare a list, initialize it with dummy data and then assign that list to your variable. That is the only way I can think of to "prevent the error". If that's all you want to do.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900