简体   繁体   中英

C#: Do I always instantiate a new reference type variable?

Which of these two cases is the most correct? This case where the rxBytes variable is only declared?

private void ParseRxData(RxMessage rxMessage) {
    List<byte> rxBytes;
    rxBytes = rxMessage.LengthBytes;
    rxBytes.AddRange(rxMessage.Payload);
    /* Do stuff with 'rxBytes' variable */
}

Or this case where the rxBytes varible is instantiated?

private void ParseRxData(RxMessage rxMessage) {
    var rxBytes = new List<byte>;
    rxBytes = rxMessage.LengthBytes;
    rxBytes.AddRange(rxMessage.Payload);
    /* Do stuff with 'rxBytes' variable */
}

In short, is it necessary to instantiate a variable when it's assigned a value immediately after it's been declared?

I'm a fairly new C#/OOP programmer, so I apologize if I'm not using terminology correctly.

The following is entirely legal syntax:

List<byte> rxBytes = rxMessage.LengthBytes;

It's not the instantiation that is required, just an assignment.

When you create a new object using the new keyword, you are allocating memory for that object. In your case, however, you allocate memory for an object and hand a reference to the object to your variable, then immediately assign that variable to point at another object. That first object immediately becomes orphaned and, eventually, garbage collected.

So really, what you are asking if you can do is not only allowed, it is a better practice for responsible programming.

In short, is it necessary to instantiate a variable when it's assigned a value immediately after it's been declared?

No - in fact if you initialize rxBytes to a new List<byte> , then overwrite the variable with rxMessage.LengthBytes , then the list you created is never used and will be garbage collected. You seem to assign it a List<byte> just so you can use var which is unnecessary. Your first code block is the correct approach.

You can also just do

var rxBytes = rxMessage.LengthBytes;

But functionally there's no difference between declaring the variable on one line and assigning it a value on another.

Is there any way to set the equal sign "by value"?

Well for reference types the "value" is a reference, but if you just want the new variable to reference a copy of the list you can do

var rxBytes = new List<byte>(rxMessage.LengthBytes);

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