Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C#, where do you use "ref" in front of a parameter?

Tags:

c#

ref

There are a number of questions already on the definition of "ref" and "out" parameter but they seem like bad design. Are there any cases where you think ref is the right solution?

It seems like you could always do something else that is cleaner. Can someone give me an example of where this would be the "best" solution for a problem?

like image 392
leora Avatar asked Apr 29 '09 20:04

leora


People also ask

What is '~' in C language?

In mathematics, the tilde often represents approximation, especially when used in duplicate, and is sometimes called the "equivalency sign." In regular expressions, the tilde is used as an operator in pattern matching, and in C programming, it is used as a bitwise operator representing a unary negation (i.e., "bitwise ...

What does the || mean in C?

The logical OR operator ( || ) returns the boolean value true if either or both operands is true and returns false otherwise.

What is & operator in C?

&& This is the AND operator in C programming language. It performs logical conjunction of two expressions. ( If both expressions evaluate to True, then the result is True.


1 Answers

In my opinion, ref largely compensated for the difficulty of declaring new utility types and the difficulty of "tacking information on" to existing information, which are things that C# has taken huge steps toward addressing since its genesis through LINQ, generics, and anonymous types.

So no, I don't think there are a lot of clear use cases for it anymore. I think it's largely a relic of how the language was originally designed.

I do think that it still makes sense (like mentioned above) in the case where you need to return some kind of error code from a function as well as a return value, but nothing else (so a bigger type isn't really justified.) If I were doing this all over the place in a project, I would probably define some generic wrapper type for thing-plus-error-code, but in any given instance ref and out are OK.

like image 115
mqp Avatar answered Oct 12 '22 23:10

mqp