With the introduction of things like duck typing, I would love it if I compose object methods on the fly, besides extension methods. Anybody know if this is possible? I know that MS is worried about composing framework on the fly, but they seem to be dipping their toes in the water.
Update: Thanks to Pavel for clarifying. For example, say I return a new dynamic object from LINQ and would like to add some methods to it on the fly.
In light of the updated answer, you're actually not looking for "dynamic methods", so much so as "dynamic objects" - such that you may add new properties and methods to them at runtime. If that is correct, then in .NET 4.0, you can use ExpandoObject in conjunction with dynamic:
dynamic foo = new ExpandoObject();
foo.Bar = 123; // creates a new property on the fly
int x = foo.Bar; // 123
// add a new method (well, a delegate property, but it's callable as method)
foo.Baz = (Func<int, int, int>)
delegate(int x, int y)
{
return x + y;
};
foo.Baz(1, 2); // 3
You can have "dynamic methods" too, with expression trees, and once you obtain a delegate for such a method, you can also create a callable method-like property out of it on an ExpandoObject.
For use in LINQ queries, unfortunately, you cannot use object initializers with ExpandoObject; in the simplest case, the following will not compile:
var foo = new ExpandoObject { Bar = 123; }
The reason is that Bar in this case will be looked up statically as a property of ExpandoObject. You need the receiver to be dynamic for this feature to kick in, and there's no way to make it that inside an object initializer. As a workaround for use in LINQ, consider this helper extension method:
public static dynamic With(this ExpandoObject o, Action<dynamic> init)
{
init(o);
return o;
}
Now you can use it thus:
from x in xs
select new ExpandoObject().With(o => {
o.Foo = x;
o.Bar = (Func<int, int>)delegate(int y) { return x + y; };
});
Yes, there is: Generating Dynamic Methods with Expression Trees in Visual Studio 2010
This was already possible with the aid of DynamicMethod and/or MethodBuilder. Not sure if that counts for being "worried", as it has been around for a while now, though it requires a dynamic assembly in most scenarios (DynamicMethod can be used without, though).
Related
I have an old compiler server (VS 2010), which, obviously, can't compile such instructions:
var result = a?.b()?.c?.d;
Is there alternative I can use? Is it possible to do this through expression tree? For example, like this:
var result = NullSafe(()=> a.b().c.d);
There were quite a few attempts to do this before it became a language feature. It's a bit hard to find the references now, but you can get an idea how it can be done and why it's not that easy.
This snippet for example looks simple:
public static R NullSafe<T, R>(this T obj, Func<T, R> f) where T : class
{
return obj != null ? f(obj) : default(R);
}
You can use it almost like an operator:
deliveryCode = order.NullSafe(o => o.DeliveryCompany).NullSafe(dc => dc.FileArtworkCode);
But it doesn't work with value types. This older snippet uses EqualityComparer :
public static TOut NullSafe<TIn, TOut>(this TIn obj, Func<TIn, TOut> memberAction)
{
//Note we should not use obj != null because it can not test value types and also
//compiler has to lift the type to a nullable type for doing the comparision with null.
return (EqualityComparer<TIn>.Default.Equals(obj, default(TIn)))
? memberAction(obj)
: default(TOut);
}
It will take a bit of digging to find more complete examples. I remember trying methods similar to these way back when until I found a more complete one.
This SO answer to a similar question does away with chaining and allows one to write:
foo.PropagateNulls(x => x.ExtensionMethod().Property.Field.Method());
The implementation is a bit involved though, to say the least.
I'm writing a Python C extension that wraps an external C library. In the original library there are structs (of type T for the sake of the discussion), so my extension class looks like this:
typedef struct {
PyObject_HEAD
T *cdata;
} TWrapperBase;
I also need to look up pointers in Python from time to time, so I exposed a read-only field _cdata that is a cdata pointer as unsigned long long (yes, I know it's not very portable, but it's out of scope now).
Then, I want to be able to add some more methods in Python, but I can't just append them to a class declared in C, so I subclass it and add my new methods:
class TWrapper(TWrapperBase):
...
Now, in my C extension code I need a way of accesing cdata field, so I can pass it to library functions. I know that self won't be an instance of TWrapperBase, but rather TWrapper (this Python version). What is the proper way to do this?
static PyObject * doStuff(PyObject *self)
{
T *cdata_ptr;
// How to get a pointer to cdata?
//
// This looks very unsafe to me, do I have any guarantee of
// the subclass memory layout?
// 1. cdata_ptr = ((TWrapperBase*)self)->cdata
//
// This is probably safe, but it seems to be a bit of a hassle
// to query it with a string key
// 2. cdata_ptr = PyLong_AsVoidPtr(PyObject_GetAttrString(self, "_cdata"))
do_important_library_stuff(cdata_ptr);
Py_INCREF(self);
return self;
}
Thanks!
// This looks very unsafe to me, do I have any guarantee of
// the subclass memory layout?
// 1. cdata_ptr = ((TWrapperBase*)self)->cdata
Yeah, that works. You can look at all the implementations of Python's built-in types and see that they do pretty much the same thing, usually without checking whether they're operating on a subclass instance.
Groovy supports both default, and named arguments. I just dont see them working together.
I need some classes to support construction using simple non named arguments, and using named arguments like below:
def a1 = new A(2)
def a2 = new A(a: 200, b: "non default")
class A extends SomeBase {
def props
A(a=1, b="str") {
_init(a, b)
}
A(args) {
// use the values in the args map:
_init(args.a, args.b)
props = args
}
private _init(a, b) {
}
}
Is it generally good practice to support both at the same time? Is the above code the only way to it?
The given code will cause some problems. In particular, it'll generate two constructors with a single Object parameter. The first constructor generates bytecode equivalent to:
A() // a,b both default
A(Object) // a set, b default
A(Object, Object) // pass in both
The second generates this:
A(Object) // accepts any object
You can get around this problem by adding some types. Even though groovy has dynamic typing, the type declarations in methods and constructors still matter. For example:
A(int a = 1, String b = "str") { ... }
A(Map args) { ... }
As for good practices, I'd simply use one of the groovy.transform.Canonical or groovy.transform.TupleConstructor annotations. They will provide correct property map and positional parameter constructors automatically. TupleConstructor provides the constructors only, Canonical applies some other best practices with regards to equals, hashCode, and toString.
I am trying to write a class in Haxe supporting array like access using the [] operator such as:
var vector = new Vec3();
trace(vector.length); // displays 3
vector[0] = 1; // array like access to the class, how?
vector[1] = 5.6; // more array access
vector[2] = Math.PI; // yet more array access
The problem is I don't know how to define a class such that it allows the [] operator. I need this class, rather than using an Array<Float> or List<Float> because there is some trickery going on with it to support my animation system which references to parts of vectors using storyboards (see http://www.youtube.com/watch?v=ijF50rRbRZI)
In C# i could write:
public float this[index] { get { ... } set { .... } }
I've read the Haxe documentation and found ArrayAccess<T>, but the interface is empty. That is I don't understand how to implement it, or if I just implement ArrayAccess<Float> ... what method on my class would be called to retrieve Float at said index?
Haxe doesn't support operators overload (yet) so you will have to use a get/set pair. You can use inline if the magic that happens inside your methods need to be optimized for speed.
I don't know if this is possible, but are there any languages where you can use a dot operator on a function per se. I'll give an example.
function blah returns type2
type 2 looks like this
{
data
number
}
when I call blah are there any languages that support blah.number, so that when it makes the function call and gets the type2, it then grabs number and returns that. I'm sorry if this is an obvious answer, but I couldn't even think of a good way to word it to google it.
I just ran into a situation that would be convienient to have that, rather then make an intermediate variable you just make sure you return the type.
I know that I could add a "get" function that would get the specific number variable from that type, but that's an additional function someone would have to add so I am excluding that as a option (as I can just return the type and access using a variable there isn't really a dire need for a new function).
EDIT: I feel like an idiot.....
EDIT # 2: For some reason I had it in my head that you couldn't do dot operations on functions, (I don't care about the parentheses I was just trying to give an example)
Edit # 3: Is there a name for this or is it still just a dot operation?
Well this works in C if the function returns a struct like this:
struct retval {
char * data;
int number;
};
retval foo() {
// do something and then return an instance of retval
}
// call
int a = foo().number;
I would like to know if there is any language that does not support something like this.
About Edit #3
The name would generally be member access, since all you do is to access a member of the return value. This could differ across languages though.
In most languages you can do Blah().Member ... the typing of a pair of parentheses won't kill you, will it? These languages include C, C++, Java, C# etc.
Yep, to the best of my knowledge, most modern languages (if not most languages in general) support this.
Maybe I misunderstand you, but in most languages, you can already do that.
in java for example, if you have a function get_foo() returning an object of type foo, and foo is defined as
Class Foo{
public int bar;
public double baz;
}
you can do get_foo().bar returning bar
Any language that allows a function to return an object/struct will support that... And languages like Ruby (where the () are optional) will make it exactly like you tiped (blah.number instead of blah().number).
Another way of avoiding the parentheses is using a property or an equivalent idiom... So C#, VB.NET and Python would also allow that.
If you want to make a new function out of an existing one, it's possible with lambda expressions. In C#, for example, it'd be var fooblah = (x => foo(x).blah); Obviously, if there's an overloading available in the language, you can't do it without giving a list of arguments.
Er...you mean, like a returning a class or a struct?
In C#
private class Blah
{
public string Data {get; set;}
public int Number {get; set;}
}
public Blah DoSomething()
{
return new Blah{Data="Data",Number=1};
}