Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can condense them all down to:</p> <pre><code>protected T GetClient&lt;T&gt;(params object[] constructorParams) { return (T)Activator.CreateInstance(typeof(T), constructorParams); } </code></pre> <p>Call it using:</p> <pre><code>AdminClient ac = GetClient&lt;AdminClient&gt;(CurrentUser); LookupClient lc = GetClient&lt;LookupClient&gt;(CurrentUser); SecurityClient sc = GetClient&lt;SecurityClient&gt;(); </code></pre> <p>etc.</p> <p>If you had all of your clients utilizing the CurrentUser (currently your example suggests that SecurityClient does not), you could remove the parameter from the method and have just:</p> <pre><code>protected T GetClient&lt;T&gt;() { return (T)Activator.CreateInstance(typeof(T), CurrentUser); } </code></pre> <p>Which simplifies your calls:</p> <pre><code>AdminClient ac = GetClient&lt;AdminClient&gt;(); </code></pre> <p>But then you lose the ability to use it on clients that don't require the CurrentUser context...</p> <p><strong>Addendum:</strong> In response to your comment regarding the requirement of a parameterless constructor. I've got some demo code that I've tested to prove there isn't a requirement for a parameterless constructor:</p> <pre><code>public class UserContext { public string UserName { get; protected set; } public UserContext(string username) { UserName = username; } } public class AdminClient { UserContext User { get; set; } public AdminClient(UserContext currentUser) { User = currentUser; } } public class SecurityClient { public string Stuff { get { return "Hello World"; } } public SecurityClient() { } } class Program { public static T CreateClient&lt;T&gt;(params object[] constructorParams) { return (T)Activator.CreateInstance(typeof(T), constructorParams); } static void Main(string[] args) { UserContext currentUser = new UserContext("BenAlabaster"); AdminClient ac = CreateClient&lt;AdminClient&gt;(currentUser); SecurityClient sc = CreateClient&lt;SecurityClient&gt;(); } } </code></pre> <p>This code runs without any exceptions and will create the AdminClient which doesn't have a paremeterless constructor, and will also create the SecurityClient which only has a parameterless constructor.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload