Is it possible to cast a Lazy<T> instance as a Lazy<object> when all I have is an object reference?
This returns null:
var result = obj as Lazy<object>;
That makes sense to me. It should be null because its not a Lazy<object>. But is there another way to interrogate to find out what T actually is or cast to object? I actually don't care what T actually is in this case. I just need the .Value reference.
Some background
So this is really a curiosity question. It could be applied to any object specifying a generic (i.e. List<T>). But here's the specific case:
I'm sticking a Lazy<T> provider in a cache. I know what T is when I put it in and I know what T is in the normal use when i pull it out.
However, in one case when I'm managing the cache, I don't know what T is and really I don't want to interact with it except to send its value to a serializer. I'm just concerned I'm missing some obvious way to achieve this without creating a way to track it ahead of time or change a bunch of method signatures/calls.
This is what the dynamic keyword is for. It uses the same reflection solution underneath as #SledgeHammer's answer, except that it has a cache for the getter delegates so it's a lot faster if you do it more than once for the same T. It's also a lot shorter and easier to read (and write).
object result = (obj as dynamic).Value;
The way you asked the question, you would need to use reflection (or expression trees) to do it:
Lazy<int> l = new Lazy<int>(() => 5);
object o = l;
object val = o.GetType().GetProperty("Value").GetGetMethod().Invoke(o, null);
Classes in C# cannot be covariant, so there is no way for you to treat that object instance as a Lazy<object>. You'll have to create a new Lazy object that simply uses the other Lazy to determine what the value should be. Doing so is simple enough:
Lazy<T> oldLazy = ComputeOldLazy();
Lazy<object> newLazy = new Lazy<object>(() => oldLazy.Value);
Related
Now, before you all rush in to tell me that question has been answered elsewhere here, for example or here, let me say it's only been partially answered, at least as far as I can see.
I have a variable of type Type and I want to create an instance of the type that t represents, so I call something like...
var inst = Activator.CreateInstance(t);
However, inst is on object and I want it to be of type t. None of the following are legal:
t inst = Activator.CreateInstance(t);
var inst = (t)Activator.CreateInstance(t);
var inst = Activator.CreateInstance(t) as t;
How do I do this? How do I get inst to be the type that I want at compile-time?
That simply isn't possible. The compiler is static typed (except for when it isn't ;p). t is a variable. variable != static. What you want to do isn't possible.
One option here is generics, but that still gets it you as a <T>, which doesn't help any if <T> still only knows about the same methods as object. Another option is dynamic; that means inst.Foo(); will work - but only at runtime, and only if the type really does have a Foo() method; importantly, the compiler still won't know about t's methods at compile-time.
From the comments, it seems that the intended usage here is for method overload resolution; dynamic can help with that - for example:
Foo(Customer cust) {...}
Foo(Order order) {...}
Foo(Region region) {...}
object inst = Activator.CreateInstance(t); // t probably one of the above types
...
Foo((dynamic)inst);
will try to invoke the most appropriate Foo overload based on the runtime type of inst, with per-type cache optimizations etc. It is a bit of a hack, but it works, and is easier and cleaner than checking manually (and thanks to the strategy cache, often more efficient too).
If the only thing you are doing with inst is passing it onwards, you could make inst itself dynamic:
dynamic inst = Activator.CreateInstance(t);
Foo(inst);
Note that you should generally be a little cautious of this, however, as once a variable is dynamic, all access to it is via the dynamic API - even a call to a method that takes an object parameter (such as string.Format) would be routed via the runtime rather than the compiler (unless of course you explicitly cast it back to object or similar).
I need to cast an object to a System.Type object.
I've read that C# is statically typed so that would not be possible.
Is this true?
If yes, how can I accomplish this?
Assembly myDll = Assembly.LoadFrom(dllData.Path);
Type manyAttribute = myDll.GetExportedTypes().FirstOrDefault(...);
Type multiplicityAttribute = myDll.GetExportedTypes().FirstOrDefault(..);
//Here is the problem
propertiesOnOtherFile = propertiesOnOtherFile.Where(t =>
t.GetCustomAttributes(false).Any(ca =>
!string.IsNullOrEmpty(((multiplicityAttribute)ca).PropertyName)));
This is the line:
((multiplicityAttribute)ca).PropertyName)
Is there any other way to do this?
EDIT:
Due to many questions, this is my scope:
public class PocoClass
{
[ManyAttribute]
public ObjectX MyProp;
}
ManyAttribute declaration
{
public string PropertyName;
}
ManyAttribute is in the dynamicly loaded DLL.
Then, as in my example above, I need to cast the customAttribute (ManyAttribute) to ManyAttribute so I check PropertyName's value.
I still don't get this... but this should work.
IEnumerable<Type> propertiesOnOtherFile = new List<Type>(); //from somewhere?
//Here is the problem
propertiesOnOtherFile = propertiesOnOtherFile.Where(t =>
t.GetCustomAttributes(false).Any<dynamic>(ca =>
!string.IsNullOrEmpty(ca.PropertyName)));
There are only two ways to access properties/methods of something without knowing its type at compile time. You're certainly in this situation:
reflection – gets fairly cumbersome very quickly, even for basic things, but allows you to do pretty much anything you want.
dynamic – makes C# behave similarly to dynamically typed languages, but does not allow you to do things like accessing a property whose name is also dynamic.
Since in your case the property names are also dynamic, I would say that the answer is no, there is no better way to manipulate objects and properties when they aren't known at compile time.
You would do well to design your architecture in such a way as to avoid accessing objects in quite such a dynamic way, but there is too little context to recommend a specific approach.
What you're attempting to do doesn't make sense.
This line: Type multiplicityAttribute = myDll.GetExportedTypes().FirstOrDefault(..); gets a Type that you're attempting to bind to, dynamically.
Then you're trying to cast against it: (multiplicityAttribute)ca)
What are you going to do once you have it cast?
Are you:
Attempting to get names of properties?
Attempting to get a list of object types that have some property?
Attempting to get the value of some static property?
Attempting to get the value of some instance property, but you don't know the name of the class that is defining the instance?
What it seems like you're trying to do is create a generalizable approach to inspecting for something that in reality is pretty specific. When working with Reflection, it's commonly easier to go the other direction: solve the specific case first, and then refactor to more generalizable approaches.
object[] objArray = new object[]{"blah", 4, "whatever"};
foreach(var value in objArray) vs. foreach(object value in objArray)
I'm curious as to what the difference is between those, other than var must remain its type after assigned. Is one better than the other? Thanks.
From a purely functional perspective, var is just a shortcut for object here, since objArray's elements are of declared type object.
Using object is a sign to whoever's reading the code that the items in the array are not known to be any type more specific than object. The use of var does not connote this. In the minimal case you posted, it really doesn't make any difference to the clarity of the program which one you use.
If, on the other hand, it is not immediately clear from the context what type of object you are working with, then it may be advantageous to explicitly declare the type. On the other hand, if the type of the elements of the collection you're iterating over is verbose and obtrusive, then it may be advantageous to use var, so that the reader's eyes will be drawn to the logic of the code rather than a mess of generic parameters.
The only difference between var and any other type is that you let the compiler determine the type.
there is no difference between those two, var would be object in this case.
In your example no. But,
When declaring objects you get:
Boxing and Unboxing
However. When using var, it is compiled exactly as if you specified the exact type name.
So var tempval = 5; is the same as int tempval = 5;
I need to change the Capacity property of the dynamic variable of type List<*DynamicType*>.
The problem is that Activator returns object-casted variable if variable type is not specified instead of proper List<*DynamicType*> and the best I can do is to cast it to IList:
DynamicTypeBuilder builder = new DynamicTypeBuilder() { ... };
Type dataType = builder.GenerateType(...);
Type listDataType = typeof(List<>).MakeGenericType(dataType);
IList list = (IList)Activator.CreateInstance(listDataType);
After some searching I found only one hack:
dynamic dynamicList = list;
dynamicList.Capacity = dataRowsCount;
Though this would be acceptable in my case I wonder if there is another way to do this.
You can do it with reflection:
var capacityProperty = listDataType.GetProperty("Capacity");
capacityProperty.SetValue(list, dataRowsCount, null);
An alternative is to write a generic method which does everything you want in a statically typed way, and call that with reflection instead. That can be a handy way of making sure you only need one piece of reflection.
Perhaps this is simpler:
object list = Activator.CreateInstance(listDataType,
new object[]{dataRowsCount});
Which should use the correct constructor?
Generics and reflection are indeed a pain in combination. The dynamic hack here is no uglier than setting it via reflection (a magic string as a literal, vs an unverified property member), and dynamic is internally optimised and cached (per-type), so I wouldn't have a problem with it. If you need to do more than just one property, you can also use dynamic to flip into a generic method, to minimise the ugly:
void Evil<T>(List<T> list, int capacity) {
list.Capacity = capacity;
// do other stuff
}
...
dynamic list = Activator.CreateInstance(listDataType);
Evil(list, dataRowsCount);
Which will invoke the generic method with the correct T. Not worth it just for 1 member, but it might be useful for more complex scenarios.
With the inception of the dynamic type and the DLR in .NET 4, I now have 3 options when declaring what I call "open" types:
var, locally implicit types to emphasize the 'what' instead of the 'how',
object, alias for System.Object, and
dynamic, disable compiler checks, adding methods/properties at runtime
While there's a lot written about these out there, nothing I've found puts them together, and I have to confess, it's still a bit fuzzy.
Add to this LINQ, lambda expressions, anonymous types, reflection... and it gets more shaky.
I'd like to see some examples, perhaps contrasting advantages/disadvantages, to help me solidify my grasp of these concepts, as well as help me understand when, where and how I should pick between them.
Thank you!
Use var to keep your code short and more readable, or when working with anonymous types:
var dict = new Dictionary<int, List<string>>();
var x = db.Person.Select(p => new { p.Name, p.Age });
Use dynamic when dynamic binding is useful, or required. Or when you need to decide which method to call based on the runtime type of the object.
Use object as little as possible, prefer using specific types or generics. One place where it's useful is when you have object used just for locking:
object m_lock = new object();
lock (m_lock)
{
// do something
}
var is exactly the same as writing the full type, so use that when a variable should be of a single type. It is often used with LINQ since you often use anonymous types with LINQ.
object is the root of all classes, and so should be used when a variable will have many different, unrelated/not inherited instances, or when you do not know the type ad compile time (e.g. reflection). It's use should generally be avoided if possible.
dynamic is for objects that are dynamic in nature, in that they can have different methods and properties, these are useful for interacting with COM as well as dynamic languages and domain specific languages.
var: I use it for keeping code short:
instead of writing:
MyFramework.MyClass.MyType myvar = new MyFramework.MyClass.MyType();
i can keep it "short":
var myVar = new MyFramework.MyClass.MyType();
var is statically type so the Type is known at compile and runtime (so helps catch typos)
dynamic very much similar to objects but not limited as it would be with the Object methods, here the Type is inferred at runtime, it would be used in cases wherein you want to achieve some dynamic behaviour.
Well for object it ain't having any such members which you would be using, Generics would be more preferred in such cases
Have look on this article it gives advantages and limitations of Dynamic keyword.