What was your "aha moment" in understanding delegates?
Posted
by
CM90
on Stack Overflow
See other posts from Stack Overflow
or by CM90
Published on 2012-06-21T18:21:46Z
Indexed on
2012/06/21
21:16 UTC
Read the original article
Hit count: 189
Considering the use of delegates in C#, does anyone know if there is a performance advantage or if it is a convenience to the programmer? If we are creating an object that holds a method, it sounds as if that object would be a constant in memory to be called on, instead of loading the method every time it is called. For example, if we look at the following Unity3D-based code:
public delegate H MixedTypeDelegate<G, H>(G g)
public class MainParent : MonoBehaviour // Most Unity classes inherit from M.B.
{
public static Vector3 getPosition(GameObject g)
{
/* GameObject is a Unity class, and Vector3 is a struct from M.B.
The "position" component of a GameObject is a Vector3. This method
takes the GameObject I pass to it & returns its position. */
return g.transform.position;
}
public static MixedTypeDelegate<GameObject, Vector3> PositionOf;
void Awake( ) // Awake is the first method called in Unity, always.
{
PositionOf = MixedTypeDelegate<GameObject, Vector3>(getPosition);
}
}
public class GameScript : MainParent
{
GameObject g = new GameObject( );
Vector3 whereAmI;
void Update( )
{
// Now I can say:
whereAmI = PositionOf(g);
// Instead of:
whereAmI = getPosition(g);
}
}
. . . But that seems like an extra step - unless there's that extra little thing that it helps.
I suppose the most succinct way to ask a second question would be to say: When you had your aha moment in understanding delegates, what was the context/scenario/source?
Thank you!
© Stack Overflow or respective owner