Mini
Mini

Reputation: 453

Setting multiple variables of different types to null in C# for memory management

Say I have a 3D double array 3dArray, and a variable of custom type Person person1. Doing this:

3dArray = null;
person1 = null;

works but looks sloppy and doing this:

3dArray = person1 = null; 

as throws an error as 3dArray and person1 can't be implicitly converted. Is there a better way to do this in one line?

Upvotes: 1

Views: 1422

Answers (3)

John Wu
John Wu

Reputation: 52280

You can do it but only if the types have some sort of relationship and you assign from specific to general. For example, this works:

    string s;
    object o;
    IEnumerable l;

    o = l = s = null;

Upvotes: 0

Jason Leverett
Jason Leverett

Reputation: 1

If you simply want it on one line,

3dArray = null; person1 = null; something_else = null;

Doesn't save anything from a typing perspective, but it is more vertically dense code.

Upvotes: 0

TomTom
TomTom

Reputation: 62127

No, there is not. C# has no special provision by which null propagates regardless of variable type. It is otherwise strong typed, so this assignment IS not legal (as the first assigment determines the variable type).

Upvotes: 3

Related Questions