Generic Parameter constraint - new()

  • Thread starter Thread starter Adam Clauss
  • Start date Start date
A

Adam Clauss

So, we can use the new() constraint to specify that a given type must have a
parameterless constructor.

Why can't we say something like new(string) to specify that it must have a
parameter taking a single string? If we can do one, why not the other?
 
Because one is more complex than the other, and new() satisfies a *lot*
of classes? I really do feel your pain though.

I can only think of two ways of doing this:
1: reflection; in the static ctor for the class, use reflection to find
(and cache) the specific ctor; if there isn't one, throw an exception;
else (later) use the cached ctor to create objects [not compile-time
safety, but the next best thing]
2: delegation; create a delegate T Constructor<T>(string value) that
must be passed to the method, and use that internally? Again, not
ideal, but it can work (and also supports factory-pattern usage with
deferred evaluation, which is quite nice).

Marc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top