Home > database >  what does it mean by putting c# code blocks inside a scope
what does it mean by putting c# code blocks inside a scope

Time:07-23

i'm learning asp.net core and on a video the guy put some lines inside a scope

var builder = WebApplication.CreateBuilder(args);
{
  builder.Services.AddControllers();
}
var app = builder.Build();
{
  app.UseHttpsRedirection();
  app.MapControllers();
  app.Run();
}

instead of the default:

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
var app = builder.Build();
app.UseHttpsRedirection();
app.MapControllers();
app.Run();

what does that mean ?

CodePudding user response:

string a = "one";

{
    a  = "!";
}

Console.WriteLine(a);

Is exactly the same thing as

string a = "one";
a  = "!";
Console.WriteLine(a);

The compiler will even strip out the extra scope (in debug mode. In release mode it crunches it even more)

Yes, the center line is in its own scope, but because you're not declaring any variables inside the scope that doesn't matter. Scopes only matter when it comes to variable declarations and determining which variables you have access to.


"Readability" is subjective, and I'd encourage you to reach out to this person who suggested adding these scopes to know their opinion on their use.

CodePudding user response:

Scope is of course different with different languages.

But, the idea to "use" or "leverage" scope in your code?

Well, take this code

  string MyTest = "Hello world";


  if (MyTest == "Hello world") 
  {
       debug.print("MyTest = Hello world");
  }

  if (MyTest == "Zoo")
  {
      debug.print("MyTest = Zoo");
  }

So, in above, the scope of MyTest is quite much global to that one function.

But, you can LIMIT the scope of MyTest, by nesting in code blocks.

In other words, if I don't need/want/have to/require the var MyTest to be glocal to that function, then I can choose to nest the var MyTest.

If I make that decision, then code later on in that function cannot use MyTest, can't accident modify that var. And even MORE interesting I can cut paste such code and USE AGAIN in the code - and that var is LOCAL to ONLY the code block.

So, I can write above as:

 if (some codition - don't really care what)

 {
      string MyTest = "Zoo Zoo";  - this is scoped to the above if block
      if (MyTest == "Hello world") 
      {
          debug.print("MyTest = Hello world");
      }

      if (MyTest == "Zoo")
     {
         debug.print("MyTest = Zoo");
     }
}

if (MyTest == "test test")   -- fail!!! - MyTEst is out of scope!!!!

So, if you declare variable(s) at that level of if block, then when you are done that if block, then the variable GOES OUT of scope!!!

So, often it kind of nice, since I can take some code from on-line, or whatever, and paste it into my existing code. But, what happens if that code uses the SAME name as existing varibles? You can't paste and re-use that code.

However, if you scope the vars to the given code block, then YES you can. And you can even re-paste that code again later on, and you don't have to worry about variables collidnig with existing variable names.

So just about ANY code block?

If you declare the vars inside that code block, then after end of that code block, those variables go out of scope - they don't exist anymore, can't accident be changed. And as noted, you can later on start a code block, and declare use variables again - EVEN with the same name.

And if you have some stray code in that block that attempts to use/modify those variables? The compiler will catch that too.

I came from a VB6, VBA back ground. When you declare a var in a sub/function?

It is scoped to the WHOLE function. IN vb.net/c#, it is not.

So, I might be typing along and go like this:

 if (some test) 
 {
     // start a new buffer
     string MyBuffer = "";
 }

 if (MyBuffer != "") 
 {
     // some buffer process code here
 }

The above will NOT work, since MyBuffer is out of scope. I have to use this:

 // start a new buffer
 string MyBuffer = "";

 if (some test) 
 {
     MyBuffer = "somthing"
 }

 if (MyBuffer != "") 
 {
     // some buffer process code here
 }

   

On the other hand, since I have the first if block, then I probably should put all fo the code inside that if block - include the 2nd if, and including the declare of that string MyTest.

So, declaring vars at or inside a code block can be a great practice, since then you limit the scope and use of the variables. That means code further down can use the same code patter, and even freely use the same variables.

I mean, do you have 5 for loops in that one code stub, and do they ALL use "i" as the counter/iterator? Well, that might not be a good idea. However, if you can declare the i var inside of each code block, the you don't care if using that "i" var will be messed up by other for loops.

Limiting scope, less code is a hallmark of software systems - the goal is to reduce scope, and thus have more independent code that don't care, and can't blow up or fail because some other code decided to use the same variable names.

And with object approach's to code, then we can often have multiple instances of a object, and thus again, not only do objects main goal is to limit scope, once again, the idea is more re-usable code. And each instance of that object can often have the same variable names inside used in many instances of that object, but since the scope of such vars is limited to the object/class, then you don't' care and are free to do so.

So, quite much most approaches to code seeks to limit variable scope - and as above shows, even a simple if/then block of code can be used to limit such scope. If you don't need that variable outside of that code block? Then it a good idea to limit that variable scope to the block of code!

The above is really all your being suggested to do here - (leverage code blocks to limit variable scope when it makes sense to do so).

 var builder = WebApplication.CreateBuilder(args);
 {
     builder.Services.AddControllers();
 }

How about better this:

 {
     var builder = WebApplication.CreateBuilder(args);

     builder.Services.AddControllers();
     // more and all code that uses builder goes here
 }

So, now place ALL OF your code that uses and needs builder inside of above. Once you exit that block - the vars are out of scope

  • Related