The Traps Lurking in C# structs
Hello. I'm Hirayama from the Technology Department. In this article I'll write about the traps I fell into when using structs in C#. I'll talk mainly from my experience with Unity, but I don't think any of this is limited to Unity.
For those in a hurry, here's the conclusion: don't use structs. If you really feel the urge to use one, go ahead, but be prepared to fall into a trap and waste time. I think you'll fail in useful ways that pay off later, and your product will probably end up performing better too, but there's probably no reason you have to use structs. You can build products without them.
However, even if you never once type the word struct, as long as you write C# you can't escape structs.
(2019/04/10) I added a supplement at the end about points where I oversimplified.
What is a struct?
C# types come in classes and structs... For that kind of overview, there's a good article, The difference between classes and structs in C#, and when to use which, so I'd recommend reading that. For primary sources, see the MSDN reference and the official programming guide.
That said, what fundamentally sets the two apart is surprisingly rarely explained. Probably it's too basic for anyone to bother, but many people have never used a primitive language like C, so I suspect it's actually not that widely known. Let me explain a little.
The heap and the stack
Variables need memory, and in some languages that memory comes in two broad kinds: the heap and the stack. C# is one of those languages.
When you new up an instance of a class, it goes in memory called the heap. It's easier to picture if you know what the English word "heap" means: "a messy pile of things". A deck of cards is a heap, and so is food piled high on a plate. Picture a place where memory lies in a messy pile, and you take as much from it as you need.
On the other hand, when you new up an instance of a struct, it goes in memory called the stack. Here too it helps to know what the English word "stack" means: "things stacked on top of each other". Boxes, plates or books piled one on top of another are a stack.
So what's the difference between "a pile of things" and "a stack of things"? A heap is a jumble, while a stack is stacked fairly neatly. The difference in programming roughly matches that image: you can access all sorts of places in the heap, but since the stack is neatly piled, you can only access the top. You can't get at the things lower down without moving the things above them out of the way.
With a struct
Look at the following code.
struct T{ int _x; }
void Foo()
{
T a = new T();
Bar();
}
void Bar()
{
T b = new T();
}
When you call Foo(), an instance of T is created on the stack and given the name a. Since T is a struct, new puts it on the stack.
When Bar() is then called, an instance of T is created on the stack and given the name b. While Bar() is running, the instance named a still exists in memory; otherwise you couldn't use a after Bar finished, right? When Bar() finishes, on the other hand, the instance named b disappears from memory.
You can think of it as b being stacked on top of a, so you can't see a unless you move b out of the way (some languages let you see Foo's variables while Bar is running, but C# doesn't). And once something is moved out of the way, it can't be used any more. It's gone for good.
Thanks to these restrictions ("you can only see variables created in the function currently running" and "they disappear when the function ends"), allocating and managing memory becomes remarkably simple, and setting up a and b in memory and freeing them costs next to nothing.
And the classic example of a struct type is int.
void Foo()
{
int a = 0;
Bar();
}
void Bar()
{
int b = 0;
}
Writing this is just shorthand for
void Foo()
{
int a = new System.Int32(0);
Bar();
}
void Bar()
{
int b = new System.Int32(0);
}
Since System.Int32 is a struct, the instances named a and b are created on the stack; when Bar() ends b disappears, and when Foo() ends a disappears.
With a class
Classes, however, are different.
class T{ int _x; };
void Foo()
{
var a = new T();
Bar();
}
void Bar()
{
var b = new T();
}
When you new up a class, the instance is created on the heap. The heap isn't stacked, so it can be accessed anytime from anywhere, and things don't disappear on their own when you leave the function. Even after Bar() ends, b is still in memory, and even after Foo() ends, a is still in memory.
In this example you can't access them after leaving the function either way, so it looks the same, but what happens under the hood is completely different.
return and assignment
Now, if variables disappear when you leave a function, what happens when you return a variable?
struct T{ int _x; };
void Foo()
{
var a = Bar();
}
T Bar()
{
var b = new T();
return b;
}
What happens when Foo() is called here is as follows.
- In Foo(), Bar()'s return value is T, and T is a struct, so first an instance of T is created on the stack and named a.
- Bar() runs, creates an instance of T on the stack, and names it b.
- When Bar() ends, b disappears, so before that a copy of b is made on the stack. This one has no name.
- Back in Foo(), the contents of the copy of b made by Bar() are copied into a.
- When Foo() ends, a disappears.
Since b disappears when Bar() ends, Foo() can't receive it; what it receives is a copy of b. And a was created on the stack before Bar() was called. new T() appears only once, yet three instances of type T show up: a, b, and the copy of b.
In other words:
- Returning a struct creates a nameless copy
- Assigning a struct with
=copies its contents. If the left-hand side is a new variable, an instance is created on the stack first
With a class, though, it's completely different.
class T{ int _x; };
void Foo()
{
var a = Bar();
}
T Bar()
{
var b = new T();
return b;
}
All I did was change struct to class, but the behavior changes as follows.
- In Foo(), Bar()'s return value is T, and T is a class, so just the name a is prepared.
- In Bar(), an instance of T is created on the heap and can be accessed through the name b.
- Bar() returns b, and when it's assigned to a, a ends up pointing at the same instance b points at.
First, since it's a class, the instance of T doesn't disappear when you leave Bar(). And for a class, assignment with = means "make the left-hand side point at what the right-hand side points at"; it isn't a copy. Here only one instance of type T is created, and no copy ever happens.
return and = behave completely differently.
Whether you write class or struct makes this much difference, and it changes behavior in all sorts of places. So let's look at the terrible things that actually happen.
The horrors of Vector3, everywhere in Unity
Unity has a type called UnityEngine.Vector3. It's a struct. So if you write
void Foo()
{
var a = Bar();
}
Vector3 Bar()
{
var b = new Vector3();
return b;
}
three Vector3 instances get created on the stack in total, and two copies happen.
The returned copy can't be modified
Now let's look at something closer to real code.
static Vector3 _v;
Vector3 GetV()
{
return _v;
}
void Foo()
{
GetV().x = 4f;
}
I've made _v static. A static struct lives neither on the heap nor on the stack, but in a fixed location, and it never disappears. So what is _v.x after Foo() runs?
Actually, this can't run at all, because it doesn't compile. What GetV() returns is not _v itself but "a nameless copy of _v". And in C#, "a nameless copy returned by a function" can't be modified, so you can't assign to GetV().x with =. This prevents the bug where you write code like the above and wrongly assume _v.x is now 4. Thoughtful design, isn't it?
The Vector3.Set() problem
But UnityEngine.Vector3 comes with a terrifying function.
var a = new Vector3();
a.Set(1f, 2f, 3f);
Set() makes a.x 1, a.y 2 and a.z 3. Handy at first glance, but it leads to accidents like this.
GetV().Set(1f, 2f, 3f);
This compiles and runs without error. And _v doesn't change at all. The "nameless copy of _v" returned by GetV() does become (1,2,3), but it isn't assigned to anything, so it just disappears.
Sadly, while C# gives you a compile error if you assign directly to something like .x, a function call that modifies the variable compiles just fine. I'm sure I'm not the only one who has thought "Right, _v is now (1,2,3)" and introduced a bug this way.
A lovely collaboration with properties
Still, if that were all, the damage would be limited. For example,
struct Vertex{ public Vector3 position; }
void Foo()
{
v = new Vertex();
v.position.Set(1f, 2f, 3f);
}
works fine, and v becomes (1,2,3). It really bares its fangs when you combine it with a lovely C# feature called properties.
struct Vertex{ public Vector3 position{ get; set; } }
void Foo()
{
v = new Vertex();
v.position.Set(1f, 2f. 3f);
}
Busted. v does not become (1,2,3).
A property is "a mechanism that makes a function look like a variable". There's a book called Object-Oriented Software Construction that moved me deeply (highly recommended), and it says something like "whether something is a function or a variable is an implementation detail and shouldn't need to be distinguishable in the interface". You should be able to use a variable without caring whether it's really a variable or a function returning a value, and I agree with that philosophy.
But using structs in C# is a different story.
Remember: when a function returns a struct, what you get is nothing but a copy. So this code can't make v.position (1,2,3). It's code that does nothing.
In practice, what happens is that you write
transform.position.Set(1f, 2f, 3f);
and think you've set the object's position to (1,2,3), but nothing has happened. I fell into this trap too when I was new to Unity.
The lesson here is don't give a struct functions that change its contents. To follow it, you either "make it unmodifiable once the constructor has run" (also called immutable: "im-" added to mutable, "changeable", gives the opposite, "unchangeable"), or "just make the modifiable variables public". You should do the former if you can, but sometimes you may go with the latter because the former hurts performance.
The hell that follows when you put them in arrays and the like
One thing I still occasionally get wrong, and get bugs from, is manipulating structs I've put in a collection such as an array.
var a = new int[10];
var b = a[4];
b = 7;
What is the value of a[4] after this runs?
It's not 7. int is a struct, and assigning (=) a struct copies it. b is a variable on the stack that has nothing to do with a, and only b becomes 7. When you write var b = ... and the right-hand side is a struct type, an instance is created on the stack. b isn't just a name but an actual value, and that's what becomes 7.
You might think, "Obviously." So do I, but can you still say that when it's written like this?
struct T{ public int x; }
Given that this is written somewhere, what is the value of a[4] after running
var a = new T[10];
var b = a[4];
b.x = 7;
?
Of course it's not 7. T is a struct, so assignment copies it, and var b = ... sets up an instance on the stack. Only b.x becomes 7, and it has nothing to do with a[4]. And yet I make this mistake fairly often, probably because I forget that I made it a struct rather than a class.
That said, in a case like this, you can just write
a[4].x = 7;
and that's what you'd actually write, but in cases like the following it's a different story.
struct T
{
public int x, y, z, w;
}
Given this somewhere, writing
a[index].x = 1;
a[index].y = 2;
a[index].z = 3;
a[index].w = 4;
is pretty tedious, isn't it? When you're, say, looping over an array and filling in the contents, writing a[index] four times is a pain.
var b = a[index];
b.x = 1;
b.y = 2;
b.z = 3;
b.w = 4;
You feel an overwhelming urge to write it like this. And then you get a bug.
Countermeasures
So what's the right answer in a case like this? One idea is to provide
struct T
{
public void Set(int x, int y, int z, int w){ ... }
}
Then you can write
a[index].Set(1, 2, 3, 4);
which curbs the urge to copy it into another variable to shorten the code. But this violates the earlier rule, "don't give a struct functions that change its contents". So what do you do?
struct T
{
public T(int x, int y, int z, int w){ ... }
}
Provide a constructor like this, and
a[index] = new T(1, 2, 3, 4);
is a lot better. A constructor can't be called after the fact, so it won't cause accidents. If you can make x, y, z and w private and even readonly, that's ideal.
However, that won't work when you need to modify it later. You might make them public and write something like
var b = a[index];
b.z = 3;
a[index] = b;
This "set up a variable, copy into it, modify part of it, then copy it back" pattern is something you do all the time in Unity; for example, to add 5 to just the y of a Transform's position, you end up having to write
var p = transform.position;
position.y += 5f;
transform.position = p;
This has nothing to do with arrays, but the problem is the same: "the code gets long and it drives you up the wall". After all, you don't want to write transform.position twice.
How to prevent it
In other words, you need to accept that when you use structs, there are times when you just have to put up with the code getting a bit longer. If you get careless and try to shorten it, you fall into the trap. That's manageable when the trap is well known, as with Vector3, but with a type you made yourself, you'll often forget you made it a struct.
This leads to the lesson that you should avoid making types other people use into structs whenever possible. My own types are one thing, but I don't want to have to check every time whether someone else's type is a class or a struct. Forcing that kind of hassle on others is not good design.
And since "your future self is someone else" and "you working on a different part is also someone else", a more practical rule follows: define structs privately inside some class.
Sometimes it can't be helped for performance reasons, as with Unity's Vector3 type, but at least don't write a function like Set(). And if you really need one, avoid properties that return structs as much as possible, and use GetHoge() or Hoge() instead. That makes it obvious it's a function. With foo.GetV().Set(4) rather than foo.v.Set(4), the problem is easier to spot.
The trap of performance dropping off a cliff
Memory allocation for structs is fast, but in exchange copies happen often, so when "there are many copies relative to allocations and frees, or the type is big", they may actually be slower. Making a type with ten or more variables a struct is probably a mistake.
Also, if you want speed badly enough to use structs, you should study closely how to use ref and out. They reduce copying. When you're tempted to return a struct, using out may be better (though I'd like to think the compiler does that transformation on its own).
But there's something far more problematic than these details.
GC Alloc hell
Look at the following code.
struct T
{
public T(int x){ _x = x; }
int _x;
}
void Foo()
{
var dictionary = new Dictionary<T, int>();
// ... do various things. For example,
if (dictionary.ContainsKey(new T(3)))
{
// something
}
}
You make a struct T, use it as a Dictionary key, and do various things with it: Add(), Remove(), ContainsKey(), TryGetValue()... all sorts of things.
But this turns out to be pretty slow. Let's see it in action with code like the following. I wrote it in Unity, but it doesn't have to be Unity.
struct T
{
public T(int x){ _x = x; }
int _x;
}
public void Foo()
{
var set = new Dictionary<T, int>();
const int N = 1000 * 1000;
for (int i = 0; i < N; i++)
{
set.Add(new T(i), i);
}
int sum = 0;
for (int i = 0; i < N; i++)
{
int value;
if (set.TryGetValue(new T(i), out value))
{
sum += value;
}
}
for (int i = 0; i < N; i++)
{
set.Remove(new T(i));
}
}
Running in the editor on Unity 2018.3.9 on a mid-2014 MacBook Pro with Deep Profile enabled, it took 6.63 seconds. I can't say whether that's fast or slow, but let's use the profiler to see what's eating the time.

It's the Dictionary operations, plain and simple. There are three of them, Add(), TryGetValue() and Remove(), but look at the GC Alloc column. TryGetValue() and Remove() each allocate 57.2MB, and Add() a whopping 70.5MB. GC Alloc means a class was newed up and an instance created on the heap.
I can see why Add() needs to new something; it probably allocates whatever the Dictionary's internal data structure needs. But why TryGetValue() and Remove() allocate is a mystery.
So let's look in more detail.

Inside TryGetValue(), it calls something called ObjectEqualityCompare.Equals(), which does a ferocious amount of GC.Alloc. It also calls something called ObjectEqualityComparer.GetHashCode(), which does a ferocious amount of GC.Alloc too.
The Dictionary's internal implementation is a hash table, so it needs to compute hash values. GetHashCode() is probably for that.
And when hash values match, it has to check whether the items really are equal, which is presumably what Equals() is for. Since T above defines neither, the default implementations get called, namely the GetHashCode() and Equals() of System.Object (or object), the base of all types (whether that's literally the case depends on the implementation, and in fact Unity's implementation here doesn't work that way, but conceptually I think that's fair).
So why are these allocating? You've probably guessed by now. It's boxing.
About boxing
System.Object is a class, but T is a struct, and you can't call a class's functions on a struct. In such cases, a process called boxing happens automatically, converting the struct into a class.
Boxing is, in effect, something like this.
struct T{ ... }
class BoxedT{ T _value; }
var boxed = new BoxedT(t);
boxed.GetHashCode();
boxed.Equals(...);
Think of it like this: for a struct T, a corresponding class called BoxedT that holds a T is defined automatically. Whenever a System.Object function has to be called, a BoxedT is newed up and the T is put inside it. BoxedT is a class that inherits System.Object, so System.Object's functions can be called on it, and when you cast back to T, the contents are taken out again (this is called unboxing).
Notice the new?
It's newing up a class, so an instance is created on the heap. That's much heavier than setting up an instance on the stack. You made it a struct to speed things up, and this ruins it.
IEquatable<T>
So what should you do? This:
struct T : System.IEquatable<T>
{
public T(int x){ _x = x; }
public bool Equals(T other){ return _x == other._x; }
int _x;
}
Make T implement System.IEquatable<T>. The required function is Equals(), which should return true if they're the same and false otherwise. This alone brought the run time down to 4.37 seconds, almost 1.5 times as fast. Let's look at the profiler.

TryGetValue()'s GC Alloc went from 57.2MB to 19.1MB, a third of what it was. The ObjectEqualityCompare.Equals() from before has vanished, and the T.Equals() I defined is called instead.
A struct can't use normal inheritance, but it can implement interfaces. If it implements System.IEquatable<T>, that's used to decide "whether two things are equal", and the cast to System.Object is no longer needed. Note that just implementing Equals(T) isn't enough for it to be used; you need to declare the interface.
Overriding GetHashCode()
Now let's deal with the other one, GetHashCode(). Is there an interface with GetHashCode(), like there is for Equals? Strangely enough, there isn't. Instead, you do this.
struct T : System.IEquatable<T>
{
public T(int x){ _x = x; }
public bool Equals(T other){ return _x == other.x; }
public override int GetHashCode(){ return _x; }
int _x;
}
Just override GetHashCode(). This brought the run time down to 3.05 seconds, twice as fast as the original. Here's the profiler.

GC Alloc for TryGetValue() and Remove() is now 0. Add()'s can't be helped.
Honestly, I don't really understand why GetHashCode() has to be overridden, or, for that matter, why overriding it is enough. All structs are "considered" to inherit from a class called ValueType, and if you do nothing, ValueType.GetHashCode() is used as the default implementation. But a struct can't have virtual functions, and can't be inherited from in the first place, so you can't cast it to ValueType or back from ValueType. I don't really get it, but I'll just accept that "that's how it is". Maybe someday compilers will improve and you won't need to do anything, but for now (Unity 2018.3.9) it seems the wasted GC Alloc doesn't go away unless you override GetHashCode().
Aside: implementing GetHashCode()
Implementing GetHashCode() is actually not easy. In the example above the content is a single int, so you can just return it, but with several variables or complex data types, producing a good value is no longer simple. Return a poor value and Dictionary or HashSet performance drops, and worse, they may not even work correctly.
GetHashCode() must always satisfy this condition:
- Things considered equal must return the same value
(It's fine for different things to return the same value.) It doesn't matter here since we're talking about structs, but it becomes a problem when you implement GetHashCode() for a class. A class's default GetHashCode() returns different values for different instances even if their contents are identical. So if you want "same contents means equal", as with string, you need to write GetHashCode() yourself. If you implement Equals() as "true if the contents match" and leave GetHashCode() as the default, you get bugs (I did exactly that just recently).
What if it were a class?
I've gone to a lot of trouble to speed up the struct, but naturally we should check how fast it would have been as a plain class. Let's see.
class T
{
public T(int x){ _x = x; }
int _x;
}
I didn't implement any interface; I just made it a class.
It took 3.28 seconds, hardly any different from the optimized struct. What did I tell you? The conclusion is "don't use structs".
Let's look at the profiler.

GC Alloc is 129MB, about 2.5 times as much as the painstakingly optimized struct version, but the speed isn't much different. new is actually surprisingly fast.
Still, the struct is faster, and above all its memory consumption is in a different league. If you think that makes it "worth the effort", go ahead and use a struct. But you'll rarely create a million instances in a product, and in practice the difference will probably be tiny. Will you still use structs, traps and all?
When using SortedDictionary or Array.Sort()
Implementing System.IEquatable<T> and overriding GetHashCode() matter when you use Dictionary or HashSet.
With SortedDictionary, or Array.Sort(), List.Sort() and so on, it's a different story: this time you need to implement System.IComparable<T>. That's because, unlike Dictionary, SortedDictionary is a search tree internally, so it needs a defined ordering.
struct T : System.IComparable<T>
{
public T(int x){ _x = x; }
public int CompareTo(T other){ return _x - other._x; }
int _x;
}
You implement CompareTo(T), which returns an int: negative if this one is smaller, positive if it's larger, and 0 if they're equal. With an int, it's as simple as a subtraction.
With this one, though, the code won't compile unless you do it, so it's unlikely to cause a nasty problem, and it isn't specific to structs either; classes need the same thing. But there's one mistake that does enormous damage only with structs.
The mistake I made the other day
What happens if you implement System.IComparable here by mistake?
struct T : System.IComparable
{
public T(int x){ _x = x; }
public int CompareTo(object other){ return _x - ((T)other)._x; }
int _x;
}
I implemented CompareTo(object) instead of CompareTo(T). You know what's coming: boxing hell from casting to System.Object, a problem unique to structs.

Sorting takes N*log(N) comparisons for N elements, so it's a complete disaster. Sorting a mere million items wasted a whopping 630MB of memory, and the run time roughly tripled.
By the way, I've seen articles that say "implement IEquatable along with IEquatable<T>", but I don't really see the point. "Doesn't compile at all" is safer than "runs, but slowly and trashing memory". I don't know how many cases actually need the untyped object versions of Equals() or CompareTo().
Summary: avoiding GC Alloc
To sum up, if you define a struct that might be put in a List and sorted, or put in a Dictionary, you should implement System.IEquatable<T>, GetHashCode() and System.IComparable<T>. Otherwise, there's no telling where a GC Alloc fest will break out.
However, as I said earlier, if you follow the rule "don't let other people use your structs", you're the only one using them (that is, they're defined privately inside a class), so you only need to implement what that class uses.
You could also take the view that falling into this GC Alloc hell is nothing to worry about. Dictionary only got twice as slow, and sorting three times. Some may think "two or three times is within the margin of error". But in that case you could just as well say so why not just use a class?, and personally I think if you care about performance enough to want a struct, go all the way. To each their own, I suppose.
Come to think of it, one thing worth remembering is that if you GC Alloc like crazy, GC.Collect takes longer later. The time GC.Collect(), that is, garbage collection, takes grows with the number of instances allocated. How much longer it actually gets depends on the implementation, so it may be fine, or it may not. To be safe, it doesn't hurt to keep that in mind too.
Closing
Let's recap the "precautions for using structs" covered so far.
- Don't provide functions that change the contents. Ideally make it "unmodifiable"; if that's not possible, just make the variables public.
- If you need functions that change the contents, don't return the struct from a property
- Define structs privately inside a class and don't expose them
- If you put them in a Dictionary or HashSet, implement System.IEquatable<T> and override GetHashCode()
- If you put them in a SortedDictionary or sort them, implement System.IComparable<T>
Note that this is my personal view, not a consensus within our company. The people at Unity, at least, would probably disagree, since I wouldn't have provided Vector3.Set().
Now, you know the most important conclusion, right?
It's "don't use structs". At my skill level, every time I use a struct I cause at least one bug and lose time. Every mistake described above is one I made myself.
I really learned a lot.
Bonus
This is slightly off the topic of using structs, but I see this a lot too.
yield return 0;
What you write after yield return is stored in IEnumerator.Current, and since IEnumerator.Current is a System.Object, a class, the 0, an int and therefore a struct, gets boxed. That's a GC Alloc, so it's slow. Return 5f and that's a float, also a struct, and a Vector3 is a struct too. The runtime may kindly optimize it away, or it may not.
Here, if you write
yield return null;
there's no such problem, because null is of type System.Object, a class.
I wonder who started this habit of yield return-ing 0? Someone must have done it first...
Supplement in response to bookmark comments
In many places I skipped too much or oversimplified, so here's a supplement.
"With the stack, you can only access the top"
By "you can only see the top", I was treating the function as the unit; I meant "you can only see variables in the function currently executing (= the top)". And that's really just how the language is designed; in practice, "everything currently on the stack" is accessible.
In fact, if function A passes a reference to a variable on its stack to function B, which it calls, B can access A's variable. It's just that the language forbids direct access.
Some languages allow direct access; in Pascal, you can also access the variables of the function that called the currently executing function.
"If a class has a struct field, it should be created on the heap. This is wrong"
Quite right. I simplified things because it's probably obvious to many people, explaining it would make the article even longer, and I didn't think misunderstanding that point leads to bugs very often. This article only deals with local variables.
class A
{
int x;
}
Given a class like this, if you new up an A, it's allocated on the heap. And int x, a struct contained in A, lives on the heap too.
If you took "structs only exist on the stack" literally, every int and float in a class would have to live on the stack, which is obviously absurd.
You can use structs without new, you know?
You can.
int a;
Since this is legal, structs can be used without new.
Vector3 v;
is legal too. However, without an assignment it starts out uninitialized, so what you can do with it is restricted until every field has been assigned. For example, you can't call functions on that instance or read its fields. Unlike in C/C++, the terrifying bug of reading an undefined value can't happen, which I think is one of C#'s strengths.
And if you call the default constructor with new, every field is initialized to its default value, so you can use it from the very next line.
var v = new Vector3();
In this case x, y and z become 0f, and you can read them and call functions from the next line on. And, as I wrote in the article, the instance is allocated on the stack rather than the heap. For structs, new or no new just means initialized or not.
It's easy to write with +=
Someone pointed out that when you want to change a single field of a property, it's simpler to write
transform.position += new Vector3(0f, 5f, 0f);
That's certainly a bit shorter. Thank you.
I suppose you can think of it as expanding to
var tmp = transform.position; // get property
tmp += new Vector3(0f, 5f, 0f);
transform.position = tmp; // set property
As long as both get and set exist and are accessible, and the + operator is defined, it looks like you can write it that way.
However, not every struct is like Vector3, letting you initialize every field with new and having + defined, so there will be cases where you can't write it like this and have to do the property's get and set separately.
Does anyone actually write yield return 0;?
If you search for yield return 0, you get quite a lot of hits.
Interview with the author of this article, Hirayama
An interview with Hirayama, the author of this article, is up on the KAYAC site. Please take a look!
A career theory of getting over walls by deliberately resetting your career so far | KAYAC