Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7417859
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 29, 20262026-05-29T07:46:44+00:00 2026-05-29T07:46:44+00:00

Given these interface and implementation interface IService {} class Service : IService {} with

  • 0

Given these interface and implementation

interface IService {}
class Service : IService {}

with a generic method

void Register<I>(I service)
{
    var type = typeof(I);
}

How to make the following lines be consistent regarding the generic type?

Register<IService>(new Service())    // type is 'IService'
Register(new Service());             // type is 'Service'

Two options are acceptable:

  • both lines are compiled using IServie type
  • second line fails to compile
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-29T07:46:45+00:00Added an answer on May 29, 2026 at 7:46 am

    As you note, Register(new Service()); of course compiles to Register<Service>(new Service());

    Assuming that you can define some logic that would pick one of the concrete type’s implemented interfaces as the interface to register (which is a big assumption), you could handle concrete types rather than having the compiler exclude them. Obviously the trivial solution is to require that the type implement only one interface, but that’s unlikely to be very useful.

    I’m thinking of something along these lines (taking Jon Skeet’s suggestion and renaming the type parameter):

    void Register<T>(T service) 
    { 
        var type = typeof(T); 
        if (type.IsInterface)
        {
            Register(type);
            return;
        }
    
        var interfaceType = ChooseTheAppropriateInterface(type);
        Register(interfaceType);
    } 
    
    void Register(Type typeToRegister)
    {
        //...
    }
    
    Type ChooseTheAppropriateInterface(Type concreteType)
    {
        var interfaces = concreteType.GetInterfaces();
        //... some logic to pick and return the interface to register
    }
    

    All things considered, it’s probably simplest and clearest to let the caller specify the desired interface with the Register<IService>(new Service()); call.

    EDIT

    I agree that Register<IService>(new Service()); is the clearest form. But how can I enforce programmers to not omit the <IService>? Re-sharper, for instance, may suggest that <IService> is redundant.

    To answer that question, let’s consider the semantics of the call. The call is associating an object (new Service()) with an interface (IService). One way to force programmers to be explicit about the identity of the interface is to make the type a formal parameter. In fact, if you’re not calling any of the interface’s methods on the object you’re registering, you don’t even need generics:

    void Register(Type serviceType, object service)
    {
        // ... some argument validation
    
        if (!(serviceType.IsAssignableFrom(service.GetType())))
            throw...
    
        // ... register logic
    }
    
    //usage:
    void InitializeServices()
    {
        Register(typeof(IService), new Service());
    }
    

    Even without calling any of the interface’s members on the object, however, there’s another benefit from generics: compile-time type checking. Is there a way to get compile-time type checking while forcing the developer to specify the type explicitly? Yes: with two type parameters in the method signature, but only one argument, there’s no way for compiler to infer both types, so the developer has to supply both. That’s more typing, but the code is more explicit.

    With that approach, you can also constrain the implementing type to the interface type, to ensure that the developer doesn’t call, for example, Register<IValidationService, SecurityService>(new SecurityService());:

    interface IServiceBase { } // interface that all service interfaces must implement; might not be needed
    interface IService : IServiceBase { }
    class Service : IService : { }
    
    void Register<TServiceType, TImplementingObject>(TImplementingObject service)
        where TServiceType : IServiceBase  // superfluous if there's no IServiceBase, of course
        where TImplementingObject : TServiceType
    {
        // ... implementation
    }
    
    //usage:
    void InitializeServices()
    {
        Register<IService, Service>(new Service());
    }
    

    or even

    class NewImprovedService : Service : { }
    
    void InitializeServices()
    {
        Register<IService, Service>(new NewImprovedService());
    }
    

    This gets us back to the point of some possibly-redundant type indications, and the call is even more verbose than what you started with, but it does prevent the developer from inadvertently registering the wrong service type.

    We are still left with the original problem, however, as there’s nothing stopping the developer from calling

    Register<Service, NewImprovedService>(new NewImprovedService());
    

    That won’t fail until a runtime check for typeof(TServiceType).IsInterface.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Using MVVM's SimpleIoc, I would like to register an implementation for a given interface,
This is easier to explain with an example. Given these two classes: public class
Given this code public interface IRepository<T> { IQueryable<T> GetAll(); } and this public class
Given the following two interfaces (these are small examples, not my actual implementation): public
Given an abstract interface and an implementation derived from that interface, where constructors are
Given a generic interface interface Foo<A, B> { } I want to write an
Given the class below does anyone know why EclipseLink implementation of JPA fails to
Given these base classes and interfaces public abstract class Statistic : Entity, IStatistic {
I need a service lookup method that returns a compatible service. These particular services
Given these two queries: Select t1.id, t2.companyName from table1 t1 INNER JOIN table2 t2

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.