C# implicit cast from base class to extended (System.Reflection.Assembly)
-
21-12-2019 - |
Question
I've been working the project mentioned c-sharp-compilerresults-generateinmemory.
I've been writing a lot of code to get my "class discovery" implemented. It works cool, but I realized it would be a lot more efficient if I implemented everything as an derived class of `System.Reflection.Assembly'.
So with that new derived class written I hit a problem. When I try to assign the base class to the new derived class it throws an error, just the normal did you miss an explicit cast
error.
I thought C# did implicit casting for extended types?
So I have some source code like this...
Assembly asm = MyCompilerResults.CompiledAssembly(); /* this works */
Interface asmInterface = new Interface();
asmInterface = asm; /* bad */
asmInterface = (Interface)asm; /* bad */
public class Interface : Assembly {
public Interface() {} // I always just declare the empty constructor.
public void Helpermethod1() {}
public void Helpermethod2() {}
public void Helpermethod3() {}
};
So as it's only the second week I've been writing C# I have to ask...
How do I add the base class to my class?
The question here... Why can't I write an implicit operator from a Base class to a Derived class in C#?
This seems to indicate my casting should work unless I'm misunderstanding the answers.
Solution
I think you missunderstood something. What you are trying to achieve is to assign base class to derived one. It's not possible on almost every case.
Consider following:
public class A
{
}
public class B : A
{
}
A a = new B();
// some code
B b = (B)a; // it is possible. Behind the scenes, variable a is of B type.
but:
A a = new A();
B b = (B)a; //IT'S NOT ALLOWED. The variable a is of type A that has
// no "knowledge" about B class.
In your case, CompiledAssembly()
returns Assembly
instance that has no any information about Interface
class, so it cannot be directly casted.
There are two options. Write wrapper:
public class Interface
{
private readonly Assembly underlyingAssembly;
publiic Interface(Assembly asm)
{
this.underlyingAssembly = asm;
}
// other methods
}
Assembly someAsm = MyCompilerResults.CompiledAssembly();
Interface interface = new Interface(someAsm);
or write extension methods:
public static class AsmExt
{
public static void SomeMethod(this Assembly asm)
{
}
}
Assembly someAsm = MyCompilerResults.CompiledAssembly();
someAsm.SomeMethod();
OTHER TIPS
You may want to acchieve something different here, which can be done by using extensionmethods
You have to create a static class which then offers the functionality to extend the object like this:
public static class AssemblyExtension
{
public static void HelperMethod1(this Assembly asm)
{
Console.WriteLine(asm.ToString());
}
}
You can then call it like this:
Assembly asm = MyCompilerResults.CompiledAssembly();
asm.HelperMethod1();