简体   繁体   中英

What does the new operator mean in this code

I'm newbe C# student, when I studied code-reading I have a problem this code

public class Solution {
    public int solution(int[] priorities, int location)
    {
        int answer = 0;
        Queue<KeyValuePair<int, int>> que = new Queue<KeyValuePair<int, int>>();
        for(int i = 0; i < priorities.Length; i++)
        {
            que.Enqueue(new KeyValuePair<int, int>(i, priorities[i]));
        }
    }

As I know the new operator operates to create instance in reference type object like this code:

Queue<KeyValuePair<int, int>> que = new Queue<KeyValuePair<int, int>>();

(so que is made in stack and new allocates memory in heap <-- I've learnt like this)

but:

que.Enqueue(new KeyValuePair<int, int>(i, priorities[i]))

In this code new acts without variables.

(Ps. I found the KeyValuePair<> is struct type I wonder why value type use "new"... we don't use "new" in value type like int a= new 3 )

I want know what happens

plz teach me

thank you

The expression new MyType() creates an instance of MyType - that is where memory is allocated.

When you write MyType m =... you just assign something to a variable. This does not allocate anything.

So those two expressions are completely independent. You can assign something you didn´t create (directly) before:

MyType m = new MyType();
MyType m2 = m; // just re-reference the instance created above, no memory allocation here

and you can also create an object and don´t do anything with it (although this is usually a bad idea):

new MyType();

In the case of que.Enqueue(new KeyValuePair<int, int>(i, priorities[i])) you create a KeyValuePair , but assign it to the methods item -parameter.

You could also store that object into a new variable and pass that to the method:

var kv = new KeyValuePair<int, int>(i, priorities[i]);
que.Enque(kv);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM