What is a type reference?

5

I was reading about the keyword ref e I came across a warning that said not to confuse passing by reference with type reference . No doubt this warning left me confused and raised more doubts about the subject, as I could not see the explanation.

Question

So, I'd like to know what type reference is?

    
asked by anonymous 29.07.2018 / 02:03

1 answer

3

Poor translation. You're talking about types by reference . I talk about this in What's the difference between Struct and Class? .

They are types that are naturally already objects pointed out somewhere and this has implications of how it is used and how it behaves. I spoke of this in Memory Allocation in C # - Value Types and Reference Types .

This ref feature is not new, it already existed since C # 1.0. It allowed you to pass types by reference, that is, you created an alias for the data, so you had a variable in the method (it was always a parameter) that pointed to a data elsewhere, and C # guarantees that this would always be local stack ).

What's new is that this ref can now be in a local variable that is not a parameter, it can be a return, and you can even create a type by value that is by reference. Confused?

Actually using a ref struct is creating a type by reference, there's no doubt about it. So the links speak of something slightly obsolete. The difference is that this is a reference type allocated in stack , before all types by reference were allocated in heap . This greatly reduces the pressure on the garbage collector . Many types do not work with lifecycle objects that require heap , but need to have a semantics of indirectly and it was a problem that both things were linked. This new feature allows short, local, auto-managed lifetime and maintains indirect access to the data, as if it were a class.

It's a huge gain in efficiency across multiple scenarios. But I know it will be underused, because most programmers only care about running and being easy on them. I have had contact with experienced programmers who do not care about these things. Believe me, some relatively new people who live here are already doing better than experienced people who think nothing of these things has value.

There is the engineer and the curious expert.

I talked about it in What's the 'in' for C #? . When you put this together with immutability gives a very interesting power.

Example:

public readonly ref struct RefRoPoint4D {
    public readonly double X;
    public readonly double Y;
    public readonly double Z;
    public readonly double W;
    public RefRoPoint4D(double x, double y, double z, double w) {
        X = x;
        Y = y;
        Z = z;
        W = w;
    }
}

I placed GitHub for future reference .

Whenever you use this you will have a pointer in the variable that will point to the actual object. It can not be used in anything that goes to the heap that has a longer lifetime than it.

    
29.07.2018 / 02:31