Instantiate different classes with the same name/namespace - c#

I have an architecture consisting of two DLLs and one executable. Both DLLs define a class with the same name and namespace, but potentially different implementations. What I would like to do is to create an object of each of those classes, and have both of them coexist at the same time.
But as we know a picture says more than a thousand words, so here you go:
The surprising thing is: it actually seems to work!
I have implemented a small prototype using lots of reflection to load the DLLs and instantiate the objects.
Now my question is: Why does this work?
Shouldn't there be a problem having both of the classes in the same AppDomain?
Is it safe to do it this way, or did I just get lucky?

A type is more than its class name and namespace. It also includes assembly information to qualify it. You can compare the AssemblyQualifiedName property of any System.Type and see that they are different.

Related

How to examine .NET assembly without using reflection

Let's say, we have class Base, and Derived, defined in Base.dll and Derived.dll respectively. Derived is derived from Base (may not be a direct sub-class though)
The problem at hand is, if we have Derived.dll at hand but Base.dll is missing, how to programmatically examine all the types in Derived? e.g. to know what types are available, their accessibility, inheritance relationship, etc
Based on my understanding, reflection (things in System.Reflection namespace) is not an option here because GetTypes() will try to load Base.dll which is not available, thus throw ReflectionTypeLoadException.
In particularly, is this something that can be easily achieved using Roslyn, or some good library?
You're looking for System.Reflection.Metadata, which exposes assembly metadata directly, without loading assemblies via reflection.
For investigate .NET assembly (types, methods etc.) you need to get that from the metadata. Roslyn its not what you are looking for.
Although it's not exactly true, because Roslyn has two types of information about your code, one is nodes and token and the other is symbols. The first don't know about relation info but the second know.
Anyway, you can do it in more than one way. I'll write two of them.
Use Mono.Cecil to open your assembly, get the main module and investigate whatever you want.
var allTypesDefinitaion = ModuleDefinition.ReadModule(assemblyPath).Types;
Use tools like CFF Explorer to investigate the relevant metadata tables. (TypeDef\Ref)

Getting interface methods from a dynamically loaded class in .NET

I've got a .dll library I'm writing that interfaces with a proprietary COM assembly. My goal is to publish my work online once it's built, however I need to remove the COM assembly as a project reference to avoid distribution of this proprietary dll. So what I'm trying to be able to do is dynamically load the assembly at runtime, and invoke methods where I need them. Traditionally I've used object reflection for unknown types, however this can get slow at times, and involves several ugly instanciations. In .NET 4.0 is there a way to cleanly get all the methods and toss them into a dynamic class/interface at runtime?
I'm currently getting the object like this:
Type myClassType = Type.GetTypeFromProgID("MyClass.Myclass.1");
object classObj = Activator.CreateInstance(myClassType);
I thought I'd be able to use Type.GetMethods(), however it only returns the generic ones (Equals, ToString, GetLifetime..., etc.). I know the class uses an interface, so I tried looking into dynamically loading the interface also. That led me to Reflection.Emit, and the Microsoft.Xrm.Sdk, which I am failing to understand so far.
If there's a way for me to invoke methods without needing to throw a bunch of BindingFlags every few lines, I'd greatly appreciate a nudge in the right direction
I do have the GUID for both the Class and the Interface if that helps at all.
If I were at your situation(and if i have understand the problem correctly):
I would separate the Interface,s library (DLL) from implementation library(DLL)
Then the implementation library would be loaded dynamically and my main source code that is
referenced to Interface library would be complied
Type myClassType = Type.GetTypeFromProgID("MyClass.Myclass.1");
myClassIntrface classObj =
Activator.CreateInstance(myClassType) as myClassIntrface;
classObj.CallSomeInterfaceMethod();
hope this will be useful pal.

Hide class members from everything except another specific assembly

I have two class libraries "MyLibrary.dll" and "MyLibraryEditor.dll" for a Unity runtime and editor extension. There are several class members inside "MyLibrary.dll" that are only intended for use by "MyLibraryEditor.dll".
My first thought was to use the internal keyword because I mistakenly thought that this constrained visibility to a namespace. Instead it is clear that this keyword limits visibility to the assembly.
What is the best way to constrain access to some class members to "MyLibrary.dll" and "MyLibraryEditor.dll" without hurting performance? Also, reflection is not an option.
I am happy to simply not document the functions, but unfortunately Intellisense (and MonoDevelop's equivalent) show these members.
If you want internals in one assembly to be visible from another assembly, you can use the InternalsVisibleTo attribute on the assembly containing the internals. See http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx:
[assembly:InternalsVisibleTo("MyLibraryEditor")]
That answered, you might want to rethink your architectural design so that you don't need to use it, since it will open up all internals to the other assembly, not only the ones that you want.
You could make the members internal but use [InternalsVisibleTo] to give access to those members to the other assembly. They'd still be visible within the same assembly as well, of course... there's no way of getting round that.
I primarily use InternalsVisibleToAttribute for giving access to internal members to test classes, and would try to avoid doing this for non-test purposes - but sometimes it can be useful.
This is not possible using pure C# concepts. You are two seperate assemblies, that is as far seperate as you can get, and there is no relationship between the two as far as .Net is concerned.
you could do some things with signing or validation to make it so it would be difficult to use one assembly without the other, but not something you can do to prevent visibility of the classes/members.

Partial classes in separate dlls

Is it possible to have two parts (same namespace, same class name) to a partial class in separate DLLs?
From MSDN -Partial Classes and Methods:
All partial-type definitions meant to
be parts of the same type must be
defined in the same assembly and the
same module (.exe or .dll file).
Partial definitions cannot span
multiple modules.
No. Partial classes are a purely language feature. When an assembly is compiled, the files are combined to create the type. It isn't possible to spread the files out into different assemblies.
Depending on what you want to do, though, you might be able to use extension methods to accomplish what you need.
No it is not possible. When the assembly is compiled the class needs to be finished.
While other answers do provide the unpleasant "No" that anyone landing on this page didn't want to see, I was struck by another thought that hasn't been mentioned here yet. If partial classes were allowed across assemblies, one would get access to private members of existing types that were not written by him, thus allowing him to manipulate them in ways that were not intended by the original author, thus jeopardizing the functionality of all inheriting classes too.
Not only that, those classes in other assemblies (and their children) would need to be recompiled to make it work. Thus it is logically not possible to allow splitting a class over different assemblies.
Note: Read #Zar Shardan's comment below. That is another very important issue, even more important than private member access.
You can use extension methods when you want to add a method to a class in a different dll.
The one drawback of this method is that you cant add static methods.
The question is why would you want to make a partial class in another assembly? You can define abstract classes and interfaces across assemblies, maybe you need to look into that.
You probably just want to create a Wrapper class within you own library, around the class in the 3rd part library. Then add whatever functionality to the wrapper class.

C# - Declaration of types within a namespace

what could be a possible use of declaring types within a namespace but not in a class.
For ex:
namespace Test
{
public delegate void Ispossible();
}
This is valid & does not generate any compilation errors but i can't think of why we would declare it this way as opposed to inside a class.
A namespace is a high-level unit of organization within .NET.
Declaring types within classes is typically frowned upon (but, as with all things, it's not a 100% rule) because it can make the types more tightly coupled and more difficult to find.
VB.NET Modules are somewhat of an exception (edit: they're really more of a compiler trick/syntactical-sugar), but normally everything in the .NET ecosystem is contained in a namespace.
Your example lends itself to reuse; if it were within a class then it would imply that delegate should only be used by that class and would likely lead to duplicate delegates needlessly being introduced.
Update: When working with only a handful of types namespaces don't seem of much use, but without them a project of any size would be an organizational catastrophe. Imagine the .NET framework without namespaces, one (probably long outdated) count puts the framework at 3500 Types.
Namespaces are like folders or drawers for documents; a few loose papers are easy to manage but if you have many pages then finding the one you need becomes painful.
Give the documentation a read, it's short and not terribly complicated (neither are namespaces) but has a couple decent points MSDN - Namespace (c#)
If it is a multi purpose delegate such as Func<TResult>, EventHandler which is not related to a particular class then you should declare it in the namespace directly.
Your phrasing ("what could be a possible use of declaring types within a namespace but not in a class."), indicates that you draw a distinction betweens "types" and "classes". There is none. A class is a type.
So, under what conditions would you want to declare a class directly in a namespace (i.e, the way it is most commonly done) ? These same reasons apply to other kinds of types.
Both namespaces and classes can be used to organize information in hierarchy. However namespaces allow to distribute definition across dll boundaries, but classes do not. Also classes require to put class name before type name, but namespaces allow to use keyword "using".
So if you want to define delegates in one namespace in different dlls, you use namespaces.
If you want to force people to prefix type name with any other name without being able to rely on namespace context then you use classes.

Categories

Resources