Reputation: 20592
If I default(RefType)
I get null
. If I default(ValType)
I get a ValType
with default
-ed properties. That's fine.
But I want a ref-type with val-type default
semantics; particularly for subtypes. Is this possible?
Say, I expose an interface, IExtension
.
Someone implements it as a class as FooExtension
How can I most easily get "default
" instances of FooExtension
as an "empty" class (and, equally importantly, types derived of FooExtension
) without having to change the implementation?
This is important to me; I need to create non-null
, "empty" instances of the derived types, so that they can be populated by a dynamic UI.
I'm guessing the answer will be something to the effect of iterating properties via reflection, but perhaps there's a better (read: cleaner) way.
I would just use structs, but the non-inheritable constraint, paired with the semantics of the types I'm describing being wrong, makes me wary (read: nope)
tl;dr: how do I get default classes like default structs, with inheritance supported implicitly.
Upvotes: 1
Views: 746
Reputation: 40798
One option is FormatterServices.GetUninitializedObject
which allocates an instance without calling any constructors. Generally, that is deeply confusing unless you eventually call one of the types constructors or initialize the object fully. As the name suggests, it is intended for creation of objects from serialized data but which might not have 0-arity constructors.
Upvotes: 1