Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare a var without initializing it... just yet

Tags:

c#

.net

var

Is there a way or a trick to do something like:

var existingUsers; // This is not possible, but i need it to be global :)
try
{
    existingUsers = Repo.GetAll(); // This may crash, and needs to be in a try
}
catch (Exception)
{
    throw new Exception("some error, don't bother");
}

if (existingUsers.Count > 0)
    {
        //some code
    }

Or maybe an alternative for what I'm trying to do?

like image 259
Gerald Hughes Avatar asked Sep 20 '25 03:09

Gerald Hughes


1 Answers

The correct answer here is to drop the use of var and to correctly specify the type of existingUsers outside the try...catch block:

List<User> existingUsers = null; // or whatever is the right type!
try
{
    existingUsers = Repo.GetAll(); // This may crash, and needs to be in a try
}
catch (Exception)
{
    throw new Exception("some error, don't bother");
}
if (existingUsers.Count > 0)
{
    //some code
}
like image 134
Jamiec Avatar answered Sep 22 '25 17:09

Jamiec