Skip to content

Instantly share code, notes, and snippets.

@xgalaxy
Last active April 24, 2019 08:40
Show Gist options
  • Save xgalaxy/6743756 to your computer and use it in GitHub Desktop.
Save xgalaxy/6743756 to your computer and use it in GitHub Desktop.
Example of working with anonymous types in Unity3d
using System;
using System.Collections;
using UnityEngine;
public class Testing : MonoBehaviour
{
void Start()
{
// In C#, this is an 'Anonymous Type'
// A new System.Type is generated for it at compile type
var anonymous = new {
Foo = "The meaning of life.",
Bar = 42,
};
Debug.Log("anonymous.foo: " + anonymous.Foo); // prints "The meaning of life."
Debug.Log("anonymous.bar: " + anonymous.Bar); // prints 42
//Debug.Log("anonymous type: " + typeof(anonymous)); // compile error
// So 'Anonymous Type' is kind of like a dynamic object in AS,
// except there are some major disavantages...
// 1) You can't add members after creation
//anonymous.Baz = "Attempt to add."; // compile error
// 2) The values are read only
//anonymous.Foo = "Not the meaning of life."; // compile error
// 3) They can't be passed around... easily
passTest(anonymous);
}
void passTest(object obj)
{
// There isn't a good way to access its members now.
// Because I don't know its type.
// However, there is a hack...
var anonymous = AnonymousCast(obj, new { Foo = "", Bar = 0 });
Debug.Log("anonymous.foo: " + anonymous.Foo); // prints "The meaning of life."
Debug.Log("anonymous.bar: " + anonymous.Bar); // prints 42
// This hack works because the C# specification says:
// If two anonymous objects are created with the same properties,
// and in the same order, the same 'anonymous type' will be
// generated by the compiler.
// Runtime error: InvalidCastException
//var bad1 = AnonymousCast(obj, new { Bar = "", Foo = 0 });
//var bad2 = AnonymousCast(obj, new { Bar = 0, Foo = "" });
}
T AnonymousCast<T>(object obj, T aType)
{
return (T) obj;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment