Passing a type to a generic class library method that is unknown - why does it work

I am working on a C # .NET solution with many reusable assemblers. Three of them:

  • WinForms assembly
  • webclient class library
  • assembly containing data model classes

I have a general method in a class library as such:

namespace Company.WebClient { public class GetData<T>() { ... } } 

However, when I call the method from the WinForms assembly, I pass in a type that the class library will not know, because it is contained in the data model assembly:

 namespace Company.WinFormsApp { public class App { public void Main() { Company.WebClient.GetData<TypeFromTheDataModel>(); } } } 

Surprisingly, it seems to work. But why does this work? The webclient node does not have a rigidly linked reference to the assembly of the data model, so I am surprised that it does not report β€œtype not found” or some such error. Is this a safe way to work or do I need to add additional links to my project (i.e. from a class library to a data model)?

+4
source share
2 answers

The library does not need to know anything about the type - after all, it does not try to use any members of this type. You can learn about T at run-time GetData - but this is not necessary at compile time.

Think - if this did not work, then LINQ to Objects will be completely broken, because you can only use it for sequences of system types!

Basically, it is absolutely safe for this.

+2
source

This is basically the point of generics. The CLR knows at runtime a specific class that defines the type that you want to use for T ; and the code you wrote in GetData says what to do with objects like T The CLR provides stitching, so you don't need to think about it.

Note that in this example you are not setting limits on T (there is no where clause). This means that everything you can do with T -type objects treats them like an object , which is not so useful. If you restricted them to, say, implement the IMoreInteresting interface, then of course it would be that both the library and the caller would need access to the IMoreInteresting definition.

+1
source

All Articles