Skip to content

Commit fd4069c

Browse files
committed
#02-ExtensionMethods
1 parent c36d1cc commit fd4069c

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

#02-ExtensionMethods/README.md

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# 02 - Extension Methods
2+
3+
*Extension Methods* allow us to add functionality to existing classes. Say for instance we want to set the X position of a Transform. We could write a private method within our class MyGameObject but as this is probably something that we could use across multiple classes, it makes more sense to create an Extension Method
4+
5+
```C#
6+
public static void SetX(this Transform transform, float x)
7+
{
8+
Vector3 position = transform.position;
9+
position.x = x;
10+
transform.position = position;
11+
}
12+
```
13+
14+
which can be called on any Transform in any class.
15+
16+
```C#
17+
Transform myTransform.
18+
myTransform.SetX(100);
19+
```
20+
21+
As *transform.position* is a property and not a variable, Extension Methods like *SetX*, *SetY*, *MoveToInTime* etc. are extremely useful as they reduce duplicated lines of code, while making the code more understandable.
22+
23+
One issue with Extension Methods is that there are no automatic null checks. So if myTransform happens to be null, then a **NullReferenceException** will be thrown when trying to call SetX. Thus we need to explicitly check for null, if applicable.
24+
25+
```C#
26+
public static void SetX(this Transform transform, float x)
27+
{
28+
if(transform == null) { Debug.LogError("transform is null"); return; }
29+
30+
Vector3 position = transform.position;
31+
position.x = x;
32+
transform.position = position;
33+
}
34+
```
35+
36+
```C#
37+
public static bool IsNullOrEmpty(this string value)
38+
{
39+
return string.IsNullOrEmpty(value);
40+
}
41+
```
42+
43+
If you are unfamiliar with Extension Methods, then I suggest you take a look [here](https://msdn.microsoft.com/pl-pl/library/windows/desktop/bb383977(v=vs.100).aspx), [here](https://unity3d.com/learn/tutorials/topics/scripting/extension-methods) and [here](http://www.alanzucconi.com/2015/08/05/extension-methods-in-c/), and start utilizing them within your projects!
44+
45+
Note that Extension Methods can be written inside any static class. Some developers like to have a single *ExtensionMethods.cs* file, others like to break the methods out into separate files, for instance *StringExtentions.cs*, *TransformExtensions.cs* etc.

0 commit comments

Comments
 (0)