DEV Community

Jesse Phillips
Jesse Phillips

Posted on

Anonymous Class

An anonymous class is a way to provide a structured type which has no name making it optimal for single use, similar to delegates/lambda.

I have been making use of this in C# to build data I serialize to Json.

// D
auto air = new class {
    auto thin = "I am real.";
};

pragma(msg, typeof(air));
// __anonclass1
Enter fullscreen mode Exit fullscreen mode

D shows us the premise, we can assign an instance to a variable and the compiler builds an internal reference to the class.

// C#
var air = new {
    thin = "I am real"
};

Console.WriteLine(air.GetType());
// <>__AnonType0`1[System.String]
Enter fullscreen mode Exit fullscreen mode

C# drops the need to specify class and field type but functions basically the same. It does print additional info about the field types.

// Go
import "reflect"
air := struct {
    thin    string
}{
    "I am real.",
}

fmt.Println(reflect.TypeOf(air))
// struct { thin string }
Enter fullscreen mode Exit fullscreen mode

Go does not have classes but structures will serve the same purpose. In this case a field type is specified like D and its value is passed through constructor. The type print out looks just like the declaration.

D has struct but they cannot be created anonymously. This is likely because D added anonymous class to make porting Java code easier (DWT is pretty cool).

// Javascript 
const air = {
    thin: 'I am real.',
};
console.log(typeof air);
// object
Enter fullscreen mode Exit fullscreen mode

With Javascript I did not use an anonymous class because I looked it up and found it is not a good idea?. I wasn't sure what I would find for a dynamic language.

Lua will get an honorable mention. It does not have classes. Meta tables allow for some interesting things, but like Javascript anonymous is basically default.

Additional Thoughts

In D if we repeat the same anonymous class structure the internal type is not reused.

// D
auto air2 = new class {
    auto thin = "I am real.";
};

pragma(msg, typeof(air3));
// __anonclass2
Enter fullscreen mode Exit fullscreen mode

If we use meta programing you can create a new object of the same type.

// D
auto air3 = new typeof(air);
air3.thin = "still exist";

pragma(msg, typeof(air3));
// __anonclass1
Enter fullscreen mode Exit fullscreen mode

Top comments (0)