Interesting thing about C#’s try catch block

21 iul.

Consider the following program:

static void Main(string[] args)
{
try
{
var vasile = GetVasile();
}
catch { }

try
{
var gogu = vasile;
}
catch { }
}

private static int GetVasile()
{
return 5;
}

What do you think will happen when you compile it? Succeed? Wrong! It will fail.

error CS0103: The name 'vasile' does not exist in the current context

Why?

The simplest answer would be that C# is block scoped. That means that if a variable is defined in one block, i.e., inside { }, that is its scope.

The compilation failure will happen also in this case.


{
var vasile = 5;
}

var notvasile = vasile;

From Microsoft docs regarding error CS013:

This error frequently occurs if you declare a variable in a loop or a try or if block and then attempt to access it from an enclosing code block or a separate code block […]

Nu fi egoist, dă mai departe să ajungă la tot poporul

Lasă un răspuns

Adresa ta de email nu va fi publicată. Câmpurile obligatorii sunt marcate cu *

Acest site folosește Akismet pentru a reduce spamul. Află cum sunt procesate datele comentariilor tale.