Why would anyone declare a variable before defining it? Please provide example

162 Views Asked by At

I'm just now learning c# (my second language, first being python) and i thought it was strange that you could declare variables before ever defining what they are. Here's what I mean:

string str;
//then later, you can do
str = "Bob" 

what's the point? is there any logical use case that makes declaring a variable before use the only/best option? Is it faster? Not a big deal, I'm just hung up on this and cant find a cohesive answer anywhere on the internet. Thanks!

(big shoutout to random people online who take their precious time to answer questions of people like me. Really shows character that there are people out there who take time to do stuff like this, so thank you!)

4

There are 4 best solutions below

0
Avinash On

Useful when you are using loops

string str;

for(int x=0;x<10; x++)
{
    str = x.ToString();
}

Console.WriteLine(str);

Now if you did declare the variable inside the loop you won't be able to access it outside.

5
A-E On

Because i don't know its value yet.

Firstly you should know the difference between those terms Declaration, Definition and Initialization.

Sometimes you need to only declare a variable without giving it a value (not initialized), that's because you don't know its value until now or even it's an instance variable (class member) in which the client of the class will pass its value at creation.

Instance variable example:

class Player{
 
  int speed; // why didn't i initialize those variables 
  String name;

 Player(String name, int speed){

  this.name = name; //it's time to initialize

  this.speed = speed;
 }
}

Some variables must wait until their values get known, like the example above.

Local variable example

bool isEven; // whether a number is even or not
for(int i = 1 ; i <= 100 ; i++){

 if((i%2) == 0){ // now, i know it's value 
   isEven = true;
  }
 else{ 
   isEven = false;
  }
 System.out.println(isEven);
}

let me know if you need some explanation of the three terms (Declaration,...) above.

Hope it helps you.

7
Aleksandar On

Think of it as defining or telling the compiler you are creating a box, which is ready to be fed information or defined later on. Or you could take another example being partitioning a drive with a certain file system being, let's say, either NTFS or ext4 - just because you are preparing your storage device to store data or information you don't necessarily have to fill it up right away.

For some code or for some solutions it might make sense to have everything declared before filling up the variables, or boxes so to speak, abstracting for the person reading the code what is about to happen. The person studying and analyzing the code would be able to immediately pick up on what is going to happen and deduct the flow and structure of the rest of the code.

In other cases you might declare and initialize/assign on-the-go.

You could also compare it to reading a book on a subject without a table of contents or reading a scientific journal without an abstract.

2
Slepoyi On

The answer is (generally) - if you want to assign a value to the variable in some inner scope and use it in the outer scope. Scope can be created by using statement, loops, try-catch.

There is already an example with loop, so I'm going with try-catch. Consider the following use-case: you are querying some storage to get user by their id and do some processing. Storage can be inaccessible due to several reasons (network failure, storage is down, etc). So it is a common practice to wrap such calls with try-catch statement to catch and log error.

// calls any storage under the hood: sql db, redis, aws, etc
private readonly IUserRepository _repo;

...

public async Task GetAndProcessUserAsync(int id)
{
    User? user;
    try
    {
        user = _repo.GetUserByIdAsync(id);
    }
    catch (Exception ex)
    {
        _logger.LogError(ex, "Error while accessing storage");
    }
    //process user somehow
    ProcessUser(user); 
}