Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Returning local variables

Coming from C++, returning a local variable was a bad idea (when allocated memory on the stack).

Now using C# I'm getting the impression it isn't a bad idea (when returning a value, not a reference).

Why is that? I understand C# uses the GC but I'm not sure what difference that would make in this case.

like image 365
Ben Y Avatar asked Mar 16 '14 03:03

Ben Y


People also ask

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is main () in C?

Every C program has a primary function that must be named main . The main function serves as the starting point for program execution. It usually controls program execution by directing the calls to other functions in the program.

What is C full form?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.


1 Answers

The problem in C/C++ is that you can return a pointer to data that is located on the stack. If you do that the pointer is invalid as soon as the stack frame is destroyed. In managed C# you can't do such a thing.

Returning locals in C# is fine. If you return a value type, the value is copied. If you return a reference, the reference itself is copied (but it still points to the same object on the heap). In either case, there's no issue.

like image 85
Brian Rasmussen Avatar answered Oct 15 '22 19:10

Brian Rasmussen