I am looking on how to get the object (or object type) that another object is created in. For example:
public class RootClass
{
public class A
{
public void MethodFromA()
{
}
}
public class B
{
public A A_object = new A();
public void MethodFromB() { }
}
B BObject = new B();
A rootAObject = new A();
public void DoMethod(A anA_object)
{
}
main()
{
/* Somehow through reflection
* get the instance of BObject
* of type B from only the info
* given in anA_object or at
* the very least just know that
* anA_object was created in
* class B and not root. */
DoMethod(BObject.A_object);
/* Same as above except know that
* this A object came from root
* and is not from B class */
DoMethod(rootAObject);
}
}
Additional Information:
This was just a quick code to simulate part of a large project I have. The problem is I have a custom class that is instantiated many many places in various other classes. This custom class has a function that should be able to call any function in it or any function in the class that instantiated it. Very generic processing, but needed. Basically I need the inverse of ".". So with objectA.objectB, I need to find objectA only from passing in objectB to some function.
Thanks!
No - this information isn't stored anywhere. Note that even if it were, it could easily become out of date, effectively. For example:
// Code as before
BObject.A_object = rootAObject;
rootAObject = null;
DoMethod(BObject.A_object);
What should that now show? The current value of BObject.A_object was created as rootAObject, but the current value of rootAObject is null. If you'd want that to show BObject as the "owner" then you're not really talking about creation at all... and at that point, you need to deal with the possibility that an object has multiple references to it.
Please give us more information about the bigger picture: what problem are you really trying to solve?
I believe what you're looking for is the property DeclaringType, defined on the System.Type instance that you're interested in. See DeclaringType documentation.
DeclaringType will only tell you the enclosing type of the code model, but what you are after is identifying object creation point.
There is no easy way to do it other than reading the individual MethodBody IL. IL code for creating an object is newobj. To implement this, you will need to read the MethodBody for every method in your assembly and identify the method that contains newobj instruction with type operand of the object type you are after.
Solved by making all my objects derive from a custom object with a parent parameter.
Related
As strange as it might sound, I want to access something that is not.
Here's an example:
int tempVar = myObject.myVar // myVar does not exist;
In reality I want the class to run a method, that would take the non-existing variable as a parameter:
object returningVariables(string variableName)
{
object desiredObject; // a concrete object that I have stored somewhere in an array inside the class
// going trough some List that contains names of all variables, when it finds it
// return it
return desiredObject;
}
I'll try to explain in a concrete example what I want to achieve and why.
I have a class that stores stats of an object: name, level, speed, size, etc.
They are supposed to be accessed trough a method StatData getStat(string statName);
Stats are created trough a method void MakeStat(). The problem began when some stats were created in the class as public variables and accessed by other classed not trough the getStat() method.
Now that the public variables are changed, deleted or new ones added it takes some refactoring to get the app working again. And it looks bad when there are mixed calls with direct access to a public variable and a method for the same thing.
Please note, I do know how to fix my code the standard way; I am merely interested if above described technique will work.
Sounds like DynamicObject would help you here. You can override different methods for of that class for whatever is being called/accessed on that object: members, invocations, etc. Using dynamic means you won't be able to use intellisense anymore however. You can find more info here.
public class MyDynamicObject : DynamicObject {
public override bool TryGetMember(GetMemberBinder binder, out Object result){
if (binder.Name == "myVar"){
result = "xyz";
return true;
}
result = null;
return false;
}
}
// Usage
dynamic x = new MyDynamicObject();
Console.WriteLine (x.myVar); // will output "xyz"
I have a solution that works, but for educational purposes I want to understand if there is a better/cleaner/right way to do it.
Problem: In my "client" app I have a dictionary Dictionary<String, PremiseObject> where the key (String) is a immutable URL to a resource (it's actually a REST URL). PremiseObject is the base type of a whole set of derived classes; thus the Dictionary actually contains a family of classes all derived from PremiseObject.
A key requirement is I want to try to 'guarantee' that no PremiseObjects get created OUTSIDE of the dictionary.
Solution: I have the following function for getting a object out of the dictionary. It either accesses the existing instance, or if it does not exist creates it:
public PremiseObject GetOrCreateServerObject(string premiseObjectType, string location)
{
PremiseObject po = null;
if (!premiseObjects.TryGetValue(location, out po))
{
string classname;
// Create an instance of the right PremiseObject derived class:
po = // gobbly-gook that is not relevant to this question.
premiseObjects.Add(location, po);
}
else
{
Debug.WriteLine("Already exists: {0}", location);
}
return po;
}
Callers do this:
DoorSensor door =
(DoorSensor)server.GetOrCreateServerObject("DoorSensor",
"http://xyz/FrontDoor");
Works great. But I think there's a pattern or design that would elegantly allow me to encapsulate the "single-instance of each object contained in the dictionary" more.
For example, callers could do this:
DoorSensor door = null;
if (!server.ServerObjects.TryGetValue("DoorSensor",
"http://xyz/FrontDoor",
out door))
Debug.WriteLine("Something went very wrong");
I'm not really what to call this pattern. My ServerObjects are "single-instanced" by location. And my GetOrCreateServerObject is like a factory that lazy creates.
But it's possible for instances to be created that don't get put into the dictionary, which could lead to problems.
Like I said, what I have works... Cheers!
UPDATE 1/26/2011 10:13PM -
I just realized a potential problem: On the server side the object represented by a location/URL can actually be multi-inherited. It is THEORETICALLY possible for an object to be both a DoorSensor and an DigitalRelay.
I currently don't care about any of those cases (e.g. for garage doors I simplified my example above; there really is no DoorSensor I exposed, just a GarageDoorOpener which includes BOTH properties for sensing (e.g. Status) and actuation (e.g. Trigger). But this puts a wrinkle in my whole scheme if I were to care. Since this project is just for me :-) I am going to declare I don't care and document it.
I would propose the following simple idea:
PremiseObject's constructor is declared internal.
A special factory object is responsible for creating (or returning an already created) instances. The dictionary is a part of the factory.
Clients are located in another assembly.
This way PremiseObjects can be created by clients only through the factory. This way you can guarantee that only single instance of object exists for each location.
A variant of the idea would be to declare the PremiseObject's constructor private, and declare the factory a friend; but (unlike C++) C# doesn't have a friend notion.
Ok you can probably avoid a parameter and a cast (in the consumer code any way) with a generic method.
public abstract class PremiseObject
{
protected PremiseObject()
{
}
public string Location { get; set; }
public static void GetSensor<T>(string location, out T sensor)
where T : PremiseObject, new()
{
PremiseObject so;
if(_locationSingltons.TryGetValue(location, out so))
{
sensor = (T) so; // this will throw and exception if the
// wrong type has been created.
return;
}
sensor = new T();
sensor.Location = location;
_locationSingltons.Add(location, sensor);
}
private static Dictionary<string, PremiseObject> _locationSingltons
= new Dictionary<string, PremiseObject>();
}
Then the calling code looks a bit nicer:
DoorSensor frontDoor;
PremiseObject.GetSensor("http://FrontDoor/etc", out frontDoor);
So I like that calling convention - if you want to stay away from throwing an exception you can change the return type to bool and indicate failure that way. Personally I wouls say that an exception is what you want.
You may prefer the call without the out parameter - but if you do that then you have to supply the type to the method call - anyway defining the factory method would look like this:
public static T GetSensor<T>(string location) where T : PremiseObject, new()
{
PremiseObject so;
if (_locationSingltons.TryGetValue(location, out so))
{
return (T)so; // this will throw and exception if the
// wrong type has been created.
}
T result = new T();
result.Location = location;
_locationSingltons.Add(location, result);
return result;
}
Then the calling code looks like this:
var frontDoor2 = PremiseObject.GetSensor<DoorSensor>("http://FrontDoor/etc");
I like both these approaches because nothing has to be repeated. The type of the PremiseObject only gets stated once - there is no need for a string defining the type.
If you want to be really, really sure that no instances of PremiseObject get created that aren't placed in the dictionary, you could make the constructors all private, and create a static constructor (for each subclass) that took as a parameter the Dictionary object you're referring to. This static constructor would check the dictionary object to make sure that there wasn't an existing instance, and then return either the new or the existing instance as required. So something like this:
public class PremiseObject
{
public static Dictionary<string, PremiseObject> PremiseObjects { get; private set; }
static PremiseObject()
{
PremiseObjects = new Dictionary<string, PremiseObject>();
}
}
public class DerivedPremiseObject : PremiseObject
{
private DerivedPremiseObject()
{
}
public static DerivedPremiseObject GetDerivedPremiseObject(string location)
{
DerivedPremiseObject po = null;
if (!PremiseObject.PremiseObjects.TryGetValue(location, out po))
{
po = new DerivedPremiseObject();
PremiseObject.PremiseObjects.Add(location, po);
}
return po;
}
}
And there are a variety of similar strategies you could use. The key is to somehow make the constructor private and only allow access to the constructor through a static method that enforces the logic of the class construction.
Perhaps you could make PremiseObject a singleton, then you wouldn't have to worry about each object in the dictionary beign a single instance?
In the general case, setting access modifiers on your constructors should do the trick of not allowing anyone external to create the objects (barring reflection). However, these would need to be internal, so anything else in the assembly would be able to instantiate them.
I suspect many of your requirements may be met by using an off the shelf dependency injection container that supports singleton instances. It feels close, but maybe not quite the same. (possibly StrutureMap, Ninject, Castle Windsor, or Unity in no particular order)
How would I get the parent class of an object that has a value of null?
For example...
ClassA contains int? i which is not set to any value when the class is created.
Then in some other place in the code I want to pass in i as a parameter to some function. Using i as the only info, I want to be able to figure out that ClassA "owns" i.
The reason for this is because ClassA also contains some other object, and I want to call this other object's value from that same function mentioned in the above paragraph.
Could also be:
public class A
{
public class B
{
public int? i;
public int? j;
}
B classBInstance = new B();
public string s;
}
{
...
A someClassAInstance = new A();
...
doSomething(someClassAInstance.classBInstance.i);
...
}
public static bool doSomething(object theObject)
{
string s = /* SOMETHING on theObject to get to "s" from Class A */;
int someValue = (int)theObject;
}
You can't. Pass an instance of A to doSomething.
class A is not the Parent (base) of its members. Just their holder.
So you cannot do what you want, passing an int or int? around doe not involve any information about the class.
The parameter that is sent to the method doesn't contain any information that you can use to determine which object it originally came from. What's sent to the method is just a copy of the nullable int, boxed in an object.
So what you are asking for is not possible. The only way to do something like that would be to analyse the call stack to find the calling method, then analyse the code in that method to determine where the parameter value was taken from.
Cant you use a dictionary or keyvaluepairs instead so that the int is linked to "s" that way? The problem is that an int is not aware of which object owns it.
Its not possible since you are passing 'i' which is a member of class B. But class B does not hold a reference to an instance of class A. An instance is required to get the value of 's' since its a non-static field.
In .net how do I fetch object's name in the declaring type. For example...
public static void Main()
{
Information dataInformation = new Information();
}
public class Inforamtion
{
//Constructor
public Inforamtion()
{
//Can I fetch name of object i.e. "dataInformation" declared in Main function
//I want to set the object's Name property = dataInformation here, because it is the name used in declaring that object.
}
public string Name = {get; set;}
}
As far as the CLR goes, there's not really a way to determine an object's name. That sort of information is stored (to some extent) in the debugging information and the assembly, but it's not used at runtime. Regardless, the object you're referring to is just a bunch of bytes in memory. It could have multiple references to it with multiple names, so even if you could get the names of all the variables referencing the object, it would be impossible to programmatically determine which one you're looking to use.
Long story short: you can't do that.
That is the variable name, not the object name. It also poses the question: what is the name here:
Information foo, bar;
foo = bar = new Information();
You can't do this for constructors etc; in limited scenarios it is possible to get a variable name via Expression, if you really want:
public static void Main()
{
Information dataInformation = new Information();
Write(() => dataInformation);
}
static void Write<T>(Expression<Func<T>> expression)
{
MemberExpression me = expression.Body as MemberExpression;
if (me == null) throw new NotSupportedException();
Console.WriteLine(me.Member.Name);
}
Note that this relies on the capture implementation, etc - and is generally cheeky.
I don't think this is possible.
But at the first place, why do you need something like this??
With my experience i have realized that if you need something weird from a compiler or a language which is not offered, then (most often) it means that there is something wrong with the approach or the logic.
Please reconsider why are you trying to achieve this.
Is it possible to allow methods and properties of the 'this' pointer to be resolved dynamically?
Put another way, can a class have a dynamic superclass?
Clarification
I would like to be able to subclass some class and access properties and methods that aren't defined at compile-time.
class MyClass : DynamicObject
{
public void ReceiveValue(object value) {
MyProperty = value;
}
}
DynamicObject provides a way for my code to get notified that set_MyProperty has been called with the argument value above, correct? I know this is possible if you use a syntax like:
var mc = new MyClass();
...
dynamic dmc = mc;
dmc.MyProperty = value;
But I want to be able to do this from within the methods of MyClass, almost as if I had done:
dynamic dmc = this;
dmc.MyProperty = value;
Does DynamicObject have me covered?
No, you can't have a dynamic base class. Aside from anything else, the system still needs to know how much space to allocate when you create a new instance of your class.
Could you explain what you're trying to achieve? There may well be ways in which dynamic would help without needing quite this behaviour.
EDIT: Okay, having seen your edit - I don't think you can quite do what you want, but if you just use the
dynamic dmc = this;
dmc.MyProperty = value;
or
((dynamic)this).MyProperty = value;
workaround it should be fine. To put it another way: the this reference is always statically typed, but you can have an expression with the value of this but with a dynamic type.
That shouldn't be too onerous unless you're doing a lot of dynamic work - in which case I'd recommend that you use a fully dynamic language instead. If you implement the bulk of your dynamic code in IronPython/IronRuby, you can easily integrate it with your C# code anyway.
This is the basis of polymorphism. The method/property called will be the one given lowest in the heirarchy of the objects type.
How about this:
class B
{
public void M(object o)
{
dynamic i = this;
i.P = o;
}
}
class D : B
{
public object P { get; set; }
}
class Program
{
static void Main()
{
var d = new D();
d.M(1);
}
}
I realize this is a tangent, but there are languages where every class's superclass is dynamic - i.e. where class name resolution is virtual and override-able.