Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Example of practical of "ref" use [closed]

Tags:

c#

ref

I am struggling how to use "ref" (to pass argument by reference) in real app. I would like to have simple and mainly meaningful example. Everything I found so far could be easily redone with adding return type to the method. Any idea someone? Thanks!

like image 618
Loj Avatar asked Jan 10 '11 11:01

Loj


People also ask

What is REF IN React with example?

Refs is the shorthand used for references in React. It is similar to keys in React. It is an attribute which makes it possible to store a reference to particular DOM nodes or React elements. It provides a way to access React DOM nodes or React elements and how to interact with it.

What is use Ref used for?

The useRef Hook allows you to persist values between renders. It can be used to store a mutable value that does not cause a re-render when updated. It can be used to access a DOM element directly.

What is the best practice to use function UseState Hook?

UseState works just as class component's state Depending on how frequently your application's data changes, it's a good idea to break state into multiple variables. As a rule of thumb, it's best to keep each state separate so that it's easy to update and submit the data.


1 Answers

The best example coming in my mind is a function to Swap two variables values:

static void Swap<T>(ref T el1, ref T el2)
{
    var mem = el1;
    el1 = el2;
    el2 = mem;
}

Usage:

static void Main(string[] args)
{
    string a = "Hello";
    string b = "Hi";

    Swap(ref a, ref b);
    // now a = "Hi" b = "Hello"

    // it works also with array values:
    int[] arr = new[] { 1, 2, 3 };
    Swap(ref arr[0], ref arr[2]);
    // now arr = {3,2,1}
}

A function like this one, cannot be done without the ref keyword.

like image 88
digEmAll Avatar answered Sep 29 '22 12:09

digEmAll