I met a task in which it is necessary to create an instance of an abstract class using reflection on C#. At the same time, it is forbidden to create heirs.
It is clear that it is forbidden to create such instances, but reflection helps to overcome this. The answers were advised to look in the source codes on the referencesource site, to look for something like an internal call to the constructor through reflection.
A hint in the task: need to find a method in the framework that directly deals with calling the constructor and simulate its logic without unnecessary checks. But I can't find. I find how to create instance of abstract class, but without initializing variables.
How can create such an instance so that class variables with values, if they exist are also initialized?
As mentioned in the comments, you can call the internal RuntimeTypeHandle.Allocate method to create an instance of an abstact class. Afterwards you can actually call the constructor. Calling an abstract method will throw a System.BadImageFormatException "Bad IL format." This allocate method only exists in the .Net Framework.
abstract class C
{
public string One;
public C()
{
One = "One";
}
public abstract void Abstract();
}
internal class Program
{
static void Main(string[] args)
{
var obj = (C)typeof(RuntimeTypeHandle).GetMethod("Allocate", BindingFlags.Static | BindingFlags.NonPublic).Invoke(null, new object[] { typeof(C) });
typeof(C).GetConstructor(Type.EmptyTypes).Invoke(obj, new object[0]);
// outputs "One"
Console.WriteLine(obj.One);
// throws BadImageFormatException
obj.Abstract();
}
}
Another horrible unsafe option to somehow obtain an instance of an abstract type could be to rewrite an existing objects type information, see: https://github.com/IllidanS4/SharpUtils/blob/master/Unsafe/Chameleon.cs
This is not possible, not even with reflection. You'll get a runtime error, as demonstrated in the comments. What is possible, is creating a proxy from an abstract class (e.g. using Castle.Core). But that is still not creating an instance of an abstract class, but dynamically creates an implementation for the abstract members. And then creates an instance of that dynamically created implementation.
Related
I have the following class layout:
abstract class GenericClass<TArgs> where TArgs : ArgsBaseClass { }
abstract class ArgsBaseClass { }
class RandomArgs : ArgsBaseClass { }
class RandomClass : GenericClass<RandomArgs> { }
Now I want to be able to create an instance of RandomClass from an instance of RandomArgs, without knowing that it should be RandomClass. I.e. somehow I need to derive the fact that RandomClass implements GenericClass<RandomArgs>.
I'm able to create an instance of GenericClass<RandomArgs> using:
void CreateSpecificInstance(ArgsBaseClass args)
{
Type genericType = typeof(GenericClass<>).MakeGenericType(typeof(args));
var genericInstance = Activator.CreateInstance(genericType, typeof(args));
// But then I need help for the following step:
Type specificType = ... // in this case RandomClass, but should be derived from 'args'.
var specificInstance = (specificType)genericInstance;
}
Any help is appreciated.
EDIT:
Basically I have multiple args classes. Each args class has a respective 'normal' class that can be initialised with this args class. Hence GenericClass<ArgsBaseClass>.
Now I want to be able to create an instance of the 'normal' class whenever I pass an instance of the ArgsBaseClass to some function (in my example named CreateSpecificInstance.
As per my comments, I guess it would be possible to create a mapping between each args class and 'normal' class e.g. using a dictionary, but whenever you add a new args + 'normal' class combination you also need to update this dictionary. Hence I guess a solution using reflection should be used here, however I don't see a solution using reflection that doesn't iterate over all classes in the assembly or namespace, hence I'm asking for help.
The most important thing to answer this question is a lot of really specific details, particular to your implementation.
So, this answer is not a specific solution, but aims to describe a set of solutions, or at least ingredients for the solution.
The most difficult thing you can encounter in this kind of problems is dynamic discovery of interfaces and types. E.g. you don't know at compile time the full list of Args types and GenericClass implementations.
If you know it beforehand, you're lucky. Just load a Dictionary<Type, Type> with the Args type as a key and the implementation type as value.
If you don't, you have an extra problem to solve: how to uniquely identify the implementation types? There are many way to solve this problem, too, but they involve some form of Assembly.GetTypes() or (better yet) using a good IoC framework (i like Autofac the most) with built in assembly scanning capabilities. You would need to solve also the problem (maybe just in principle, but it's a question you need an answer for) of what happens if you find two implementations for the same args.
Back to our implementation type. We have an Args instance or type, we have our dictionary of types, so we find the Type of the correct implementation of GenericClass<TArgs>. Now you need a way to build instances. If you can ensure you have a parameterless constructor, you can just call Activator.CreateInstance(myGenericType). This will give you an instance of RandomClass, boxed inside an object.
You will need to cast it in some way, in order to use it, maybe to GenericClass<RandomArgs>.
If you do not have a parameterless constructor, and you can, try using an IoC container to make the hard work of discovering the constructor depencencies for you. Again, Autofac is a nice candidate, but there are a lot of alternatives and this is a deep rabbit hole.
So, in easiest case, you just need something like this:
private Dictionary<Type, Type> _implementations =
new Dictionary<Type, Type>();
public void RegisterImplementation<TArgs, TImpl>()
where TArgs : ArgsBaseClass
where TImpl : GenericClass<TArgs>, new()
{
_implementations[typeof(TArgs)] = typeof(TImpl);
}
public GenericClass<TArgs> MakeClass<TArgs>(TArgs args) where TArgs : ArgsBaseClass
{
var implementationType = _implementations.TryGetValue(typeof(TArgs), out var t)
? t
: throw new ArgumentException("The args type " + typeof(TArgs) + " is unrecognized.", nameof(args));
return (GenericClass<TArgs>)Activator.CreateInstance(implementationType);
}
I decided to go another route and use the Factory Method Pattern instead.
I was unclear in an earlier question I ask so I will try to be more explicit.
Is there a way to put a static class inside of a dictionary so that its functions can be called? If this is not possible, what is the best alternative that doesn't involve using instances that you can suggest?
Here is how I would like to use it:
static class MyStatic : IInterface
{
static void Do(){}
}
static class MyStatic2 : IInterface
{
static void Do(){}
}
class StaticMap
{
static Dictionary<Type,IInterface.class> dictionary = new Dictionary<Type,IInterface.class>
{
{Type.1, MyStatic}
{Type.2, MyStatic2}
};
}
// Client Code
class ClientCode
{
void Start()
{
StaticMap.dictionary[Type.1].Do();
}
}
There are some fundamental reasons why you can't do that directly:
Static method calls are bound at compile-time
Static calls are not inherited - they are tied to the class that defines them
There is no implicit base type (and therefore no polymorphism) between static methods, even if the name, inputs, and outputs are all the same
Since your signature is the same for every static method, you could store a Action in the dictionary instead:
static Dictionary<Type,Action> dictionary = new Dictionary<Type,Action>
{
{Type.1, MyStatic.Do}
{Type.2, MyStatic2.Do}
};
then you can call the Action directly:
void Start()
{
StaticMap.dictionary[Type.1]();
}
It's slightly repetetive because you have to specify the method name in the dictionary as well, but it's type safe.
A key question is whether you want to call a single method on each type or whether you need to call multiple methods belonging to each type.
If it's just a single method, then what D Stanley suggested is the answer. If you store a number of Actions, each representing a method with the same signature on a different static class, then you're accomplishing what you said.
However that raises a question - why the constraint that each method must belong to a separate static class? This approach would work just as well if some or all of the methods belonged to the same class.
If you need to call more than one method from each class then an Action no longer works. You'd have to store collections of Action, which a) means class instances, and b) is a lot more complicated than just using interfaces and class instances.
One way to manage instances is by using a dependency injection container to create class instances for you. Using that approach, you can create non-static classes without having to go through the hassle of explicitly making them singletons. But you can tell the container to only produce one of each and reuse it. For example, using Castle Windsor:
container.Register(Component.For<ISomeInterface,SomeClass>));
Now every time the container is asked to provide an instance of ISomeInterface it will always provide the same instance of SomeClass.
Because the dependency you're looking for varies by type (Dictionary<Type, Something>) it sounds like what you're looking for might be related to generics. But it would be necessary to take a step back from the smaller problem and understand a slightly larger picture of what you're trying to accomplish.
Instead of having the entire class as static, create a Singleton instance.
public class Foo
{
public static Foo _Foo;
public Foo()
{
_Foo = this;
}
}
Then you may add it to your list, and also inherit from Interfaces, etc.
As per the definition
Non static things can not be accesses in static context
then how does it allow to create an object of non-static class to the static main method.
class Test
{
static void Main()
{
Base x = new Derived();
x.Foo();
}
}
This is not the right definition. Here is one from MSDN:
Static methods and properties cannot access non-static fields and
events in their containing type, and they cannot access an instance
variable of any object unless it is explicitly passed in a method
parameter.
Note that you are not accessing nont-static members of Test, and neither you are using some outer variables.
Compare this, which is not allowed, to your snippet:
class Test
{
int t = 1;
static void Main()
{
Base x = new Derived();
x.Foo(t); // not allowed!
}
}
You understand that completely wrong. Static methods can't access the instance members, because they don't have the this reference. That isn't a prohibition, simply a fact of a missing reference. If you supply the reference (eg. through method parameter, creating an instance inside etc.), there's nothing to stop you from doing the call.
In other words,
class Test
{
int testField = 23;
static int GetTestField()
{
// Doesn't compile - static methods don't have a
// `this` reference to get the instance member
return testField;
}
}
Fails to compile. However,
public class Test
{
public int testField = 23;
}
public static class Tester
{
public static int GetTestField(Test test)
{
return test.testField;
}
}
works just fine, because you pass the instance of Test you're trying to access.
You're not forbidden from using instance members in static methods (that would make them almost useless!). You just don't have a this reference, as simple as that.
Not really for Stack Overflow, but okay:
To understand this, it's helpful to know something of what's going under the hood. Basically, the CPU doesn't really have a notion of things like "classes" or "methods". That's why higher level programming languages invented calling conventions - common ways to invoke methods and pass them parameters. So, for example, if you wanted to call Print(23);, it might do something like this:
push 23
call Print
The Print method would then know it's parameter is store on top of the stack, and it could retrieve it using the current stack pointer, for example.
When classes came around, they brought a concept known as encapsulation. Basically, the class effectively has its own memory storage, and its own methods. When you want to access that data (or functionality), you have to do it through the class instance. On the lower level, this is usually handled by passing the reference to the object as the first parameter of the method. So, calling test.GetTestField(23, 21) (where test is a reference to an instance of the Test class) would do something like this:
push test
push 23
push 21
call Test.GetTestField
(this is all pseudo-code, the actual way the compiler handles that differs between calling conventions and languages; for example, parameters are often sent in reverse-order)
This way, the GetTestField method has access to the instance of the Test class (which it may or may not need for what it does). So when the method has to get the value of an instance field, for example, it can get this.testField (in C# and most other languages, the this can be ommited and is implied - everytime you access an instance field/method/etc. inside a class, it adds the this under the covers).
Static methods don't have this luxury - but that's also why they exist in the first place. They're used for functionality that is related to the class in which they are defined, but they don't require the instance members of the class (or they get the instance reference some other way).
Example - there's an int class in .NET framework (actually, it's a struct, but let's ignore that for now). The class has a couple of static methods, and a couple of instance methods. For example, the instance method ToString() takes the value of the int, and converts it to a string value - for this, it (obviously) needs to have the value of the integer. On the other hand, it has a static method Parse(string), which takes a string parameter with the string value of the integer, and converts it to an integer. It creates a new integer, and parses the string value into it as an integer value. Since it creates a new instance of integer, it doesn't actually use this, and as such, can be safely declared as static. This avoids some extra costs of instance methods (even more so in languages where methods are virtual by default), at the very least, passing the extra parameter, but more importantly, it broadcasts the intent of the method - "I don't read or modify the instance members of this class". If you didn't have static methods, and you wanted to write the Parse method mentioned above, you'd have to create an instance of int first and call Parse on that.
you need to remember that you are not accessing the Foo() directly but with the help of instance variable x.That is always possible.
Note : you can not access non static members as below:
void Foo()
{
}
static void Main()
{
Foo();//compile error
}
You absolutely can access non-static members in a static context, as long as you have a valid reference to an object.
The only reason a static context is different from a non-static context in this regard, is that the static context doesn't have the this reference (which is implied when you access non-static members without explicitly referencing an object). The non-static context, on the other hand, always has an implicit this reference.
The problem isn't that you can't access non-static fields/methods/etc in a static context, it's that you can't access non-static fields/methods without an instance.
In the code you provided, there is an instance of Base, and so you can access it's methods, regardless of the context.
You can make object of non-static class in static method but could not access the non-static member int that class. Suppose you have an object of Derived class as a member of Test then you wont be able to access that object in static method main.
Define a non-static method in Test class and try to call it from Main method you will get error again.
class Test
{
Derived d = new Derived();
static void Main()
{
// You can not access d here.
// You can not access MyFun() here.
}
void MyFun()
{
}
}
I have a class called initialize that runs at the beginning of my program. Originally I explicitly hard coded all the classes that it was supposed to instantiate but I would like to make it more generic and remove the hard coded classes so I can mark the class closed for modification.
My first thought was to create a queue of Types that my initialize class would cycle through and instantiate all the Types that are in the queue.
I then wanted to decide on a per class basis if it should be added to the queue or not. By adding itself to the queue from within the class. The problem is that I cant add a class to the queue unless it is already been instantiated. I know that variables can be initialized before running but obviously not methods. So Im stuck on figuring out weather what I would like to do is possible on not.
Something along the Lines of:
MyClass
{
initalize.instance.Enqueue(typeof(MyClass));
}
I meant something along these lines.
public static class Initializer
{
public static void Initialize()
{
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
foreach (var type in assembly.GetTypes())
if (type.IsDefined(typeof(InitializeAttribute), true))
Console.WriteLine("Need to initialize {0}", type.FullName);
}
}
[AttributeUsage(AttributeTargets.Class)]
public sealed class InitializeAttribute : Attribute
{
}
[Initialize]
public sealed class ToBeInitialized
{
}
The pattern that you're looking for, if I understand your question correctly, is the factory method pattern. Take a look at this link: http://en.wikipedia.org/wiki/Factory_method_pattern#C.23
If you're initializing class static state then this isn't necessary. Just add a static constructor to all of your types and the .NET runtime will lazily call the static constructor before any static members of that class are accessed (be it a field, method, property or event). This can also work for the singleton pattern - however as I said, static constructors are JIT-evaluated which can introduce non-deterministic delays in your program.
The alternative is to use reflection to iterate through each Type in the assembly and perform your own initialization. This is how plugin systems work.
I use Resharper tool in visual studio
Consider a very simple class written below.
class Test()
{
//constructors do not have any return type.
Test()
{
System.Console.WriteLine("Hello World!");
}
static Test()
{
System.Console.WriteLine("Hello World in Static constructors");
}
public void A()
{
System.Console.WriteLine("A simple function in a class");
}
}
class Program
{
static void Main(string[] args)
{
var asa = new Test(); //Implicitly Typed local variables.
asa.A();
}
}
Using var (the compiler has to infer the type of the variable from the expression on
the right side of the initialization statement).
I have some clarification questions and they are below.
Extra burden to compiler?
How many constructors a class can have?
Why is static constructor called first ? (I checked out by putting a breakpoint?)
Why not Test asa = new Test(); is not preferred by Resharper?
Is it really a good idea to use Resharper first as a beginner? (Myself being a newbie to C and .net programming!)
Thanks in Advance.
Any extra burden to the compiler is basically irrelevant - it should not be part of your decision about whether or not to use var. As noted in comments, it may well require slightly more work for the compiler when you use explicitly declared variable... but again, it's not going to be significant.
A class can have any number of constructors... although it will become unwieldy pretty quickly.
The static constructor will be called once, before the first use of the class (whether that's via a static method or a constructor call). Read the C# spec for more details - section 10.12 of the C# 5 spec includes:
The static constructor for a closed class type executes at most once in a given application domain. The execution of a static constructor is triggered by the first of the following events to occur within an application domain:
An instance of the class type is created.
Any of the static members of the class type are referenced.
You can configure ReSharper to suggest alternatives, or treat them as warnings, etc. Make it work however you think it should, on this front.
Negligible if any. The return type would otherwise be compile checked. You shouldn't base decisions on it, anyhow.
As many as you want as long as they are distinguishable.
Static constructors are part of the type definition. They are invoked when the type is first referenced.
What message are you receiving? R# is configurable.
Edit:
(You can't beat the Skeet).
yes, there is some extra work required, but it is possible to use var keyword only in those situations in which it is pretty easy for the compiler to infer the type.
There is no constraint on number of constructors, but there are some rules constructors have to follow (ie: it needs to be clear for the compiler which constructor to call)
I can't telly you why - let's say this is just one of the rules. The interesting thing is beforefieldinit (http://stackoverflow.com/questions/610818/what-does-beforefieldinit-flag-do, http://csharpindepth.com/Articles/General/Beforefieldinit.aspx)
I personally think that in this case it is just a matter of taste. Some people tend to use var as much as they can, while others do the opposite. I try to use when:
I am working with collections (or it takes a lot of text to tell the compiler about the type: instead of:
Dictionary<<OneOfMyClasses, OtherClasss> dictionary = new Dictionary<OneOfMyClasses, OtherClass>();
I tend to use var:
var dictionary = new Dictionary<OneOfMyClasses, OtherClass>();
Please mind that it doesn't affect readability of the code (i.e. it is still easy to understand what is actually happening).
Thanks Everyone. After some time spent on research, I would like to add some points that might help someone.
Disclaimer:(The following points were derived(or even pasted) from codeproject and other such websites.
1) Every single class can have only one static constructor.
Reason: Static constructor must be parameter-less or simply, constructor overloading is not permitted. And since CLR is going to call this constructor, we do not have any control over passing values to this function. As we directly can’t call static constructors, there is no point in having multiple static constructors.
class Test
{
static Test() {...}
static Test(int a) {...} //would throw error as "Static constructor must be parameter less"
}
2) Static constructor should be declared without any access specifier.
Reason: Again CLR is going to call the static constructor not any object of the class. Hence, we donot need any access-specifier.
3) Static constructor must operate only on static variables of that class
Reason: Non-static members are specific to the object instance. There is no point in modifying a variable whose value depend/bind to their specific object instance.
4) Why should I use a static constructor ? Give me one good example
Reason: You can use a static constructor, say when you want to log the operations that you are going to perform using that class. MSDN says "A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file".
5) When exactly a static constructor is called ?
Answer: The user has no control on when the static constructor is executed in the program.
.As others and MSDN points out "A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced."
6)When using base class and derived class in C#, when a new instance of a derived class is created, does base class constructor is called first or derived class constructor is called first?
Answer: The base class constructor is called first and then the derived class constructor.
Code example
class DerivedClass : ParentClass
{
public DerivedClass()
{
Console.WriteLine("Derived class constructor!");
}
}
class ParentClass
{
public ParentClass()
{
System.Console.WriteLine("Parent class constructor!");
}
}
class Program
{
static void Main(string[] args)
{
var a = new DerivedClass(); //Implicitly Typed local variables.
}
}
7) Why in your above examples, both constructors have public access specifier ? What if I specify private or do-not specify access specifier at all?
Answer: When you do not specify access specifier(this case, the constructor automatically becomes private) or whenever you use a private access specifier, the class cannot be instantiated. Whenever a class contain one or more private constructors it strictly (!) cannot be instantiated. This type of constructors are called special instance constructor and is generally used when all the members of a class are static methods. (Probably the Math class should be a good example.)
**8)Bonus question on inheritance. Does a class inherit from two different classes ?
Strictly No. C# supports only direct inheritance and ofcourse you can use interfaces.For example,
interface Test
{
void abc();
}
class DerivedClass : ParentClass, Test //Test should not be a class. It can be a interface.
{
public DerivedClass()
{
Console.WriteLine("Derived class constructor!");
}
public void abc()
{
//should be publicly defined!
//non public method could not implement from interface Test
}
}
class ParentClass
{
public ParentClass()
{
System.Console.WriteLine("Parent class constructor!");
}
}