SCOPES IN PROGRAMMING

Sudhanshu Jain
2 min readDec 27, 2019

This is one of the important topic which explained in the book in a very short sentences. Lot of programmers are not interested because they are not known about the POWER OF SCOPE.

What does Scope means ?

Scope defines the block of the body in which variable survive.

Local variables is used where the scope of the variable is within the method in which it is declared. They can be used only by statements that are inside that function or block of code.

Global variables are declared outside any function, and they can be accessed (used) on any function in the program.

But here is the catch, If I say that you pass one object in the method which will return some values using the object properties without returning that object using “return” keyword.

Confusing ?? HOW !!!!!!!!!!!!

C# PROGRAM

In this particular example, I have created one class as “EmployeeModel” which is having two properties as “Id” and “Name”. Along with that I have created one method as Get in main method which is taking one parameter as EmployeeModel object and whose return type is “void” and returning some data using that object and printing on the console.

OUTPUT

But how the memory is working behind the scene :

The above case called as “COPY OBJECT”. As we all know, the object is only created when we use “new” keyword until then the object won’t be initialized. As per the above diagram, when “e” object copied to “f” object which directly says that now f object will also point to the same memory location where e was pointing out. In such kind of cases we don’t need to return the object instead we can use that object directly into the caller function.

I hope you enjoy this trick and understand the power of scoping in PROGRAMMING.

Hit claps if you like this blog.

--

--

Sudhanshu Jain

Senior Software Engineer | Scrum Master Certified | Blogger | Tech Mentor