Does D have class' attributes like C#'s?

Jonathan M Davis newsgroup.d at jmdavisprog.com
Sat Dec 16 21:49:33 UTC 2017


On Saturday, December 16, 2017 21:11:43 Marc via Digitalmars-d-learn wrote:
> On Saturday, 16 December 2017 at 20:05:15 UTC, Anonymouse wrote:
> > On Saturday, 16 December 2017 at 19:57:30 UTC, Marc wrote:
> >> C# has a quite nice way to store metadata about a property by
> >> a feature called atributes[1]. For example, I can write
> >>
> >> something like this:
> >>> class A {
> >>>
> >>>    [TextSize(256)]
> >>>    string Name { get; set; }
> >>>
> >>> }
> >>
> >> So using runtime/reflection I can retrieve the TextSize value
> >> associated to A.name property.
> >>
> >> Does D have something similar?
> >
> > UDAs? User Defined Attributes.
> >
> > https://dlang.org/spec/attribute.html#UserDefinedAttribute
> > http://ddili.org/ders/d.en/uda.html
> >
> > class A {
> >
> >     @TextSize(256)
> >     string name() { /* ... */ }
> >
> > }
>
> I can't "pack" an object, right? In C#, TextSize is a class and
> 256 is constructor's first argument. In D it's pretty much an
> array but I guess it's close enough. Thanks!

What do you mean by pack? You can mess with the alignment of a struct to
reduce how much space it takes up if that's what you're talking about:

https://dlang.org/spec/struct.html
http://ddili.org/ders/d.en/memory.html

But you can't do that with classes. The compiler controls their  layout and
can muck with it if it thinks that that makes it more efficient or whatnot,
whereas structs have the layout you tell them so that they can match up with
C structs as well as be used for managing how things are laid out in memory.

As for string being "pretty much an array," it's exactly an array. string is
just an alias for immutable(string)[], and underneath the hood, dynamic
arrays are essentially

struct DynamicArray(T)
{
    size_t length;
    T* ptr;
}

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list