In C# I can have references of methods and static methods. Can I also get the reference of a classes constructor?
In Java I can say Supplier<MyClass> createMyClass = MyClass::new (instead of the longer lambda syntax).
In C# I only know the notation Func<MyClass> createMyClass = () => MyClass(). But I think the Java way with the constructor reference is better readable.
And I don't want to make a static CreateMyClass function. I really want the constructor.
No, there's no equivalent of method group conversions for constructors, or properties, indexers or operators.
It's an entirely reasonable idea, but it isn't in C# at the moment. It is, however, tracked as part of a feature request in the C# design repo - so you may want to subscribe to that issue.
More particularly, I really want an immutable/shared linked list, and I think having immutable maps and sets would be nice too. As long as I don't have to worry about the core implementation, I can easily add extension methods/subclass/wrap it to provide a reasonably slick external interface for myself to use.
Is there any reason I shouldn't do this? Performance, incompatibility, etc.?
FSharpx includes a couple of "adapters" so that F# collections can be used more comfortably in C#. Here's a short example:
var a = FSharpList.Create(1, 2, 3);
var b = a.Cons(0);
b.TryFind(x => x > 4)
.Match(v => Console.WriteLine("I found a value {0}", v),
() => Console.WriteLine("I didn't find anything"));
There's not much documentation right now, but you can use the tests for reference. It doesn't include absolutely every operation (I don't mind directly using things like MapModule in C# too much), but if you find anything you need missing, please fork the repository and add it!
I also blogged about this a few weeks ago.
Or you can try and use one of these implementations of persistent collections in C#.
The types in the F# library (such as Set, Map and list) were not designed to be used from C#, so I wouldn't generally recommend using them directly. It can be done and some basic operations will work well (e.g. adding elements to an immutable map and checking if an element exists). However, there are some issues:
F# also has functionality in modules (MapModule for an immutable map) and as a C# user, you would expect to see these as members.
F# functions are not represented as Func<_, _> delegates, but using some special F#-specific way. This means that using higher-order functions will be difficult.
So, in summary, I think that a better approach is to wrap the F# data type into a class (implemented in F#) that exposes the methods you need to a C# developer in a friendly way. You can e.g. easily declare an F# method that takes Func<_, _> delegate and calls F# higher-order function in a module.
Apparently the following is valid in c# 4.0 regardless of the type of the object returned by GetADynamicThing()
dynamic d = GetADynamicThing();
d.Foo();
And if the runtime type of d does not contain a method Foo(), a RunTimeBinderException is thrown.
Will there be an easy way to determine if Foo() exists on d?
Otherwise, we're stuck doing old school reflection on the object, or relying on try-catch. Not sure I like either approach.
Update: So we have currently have 3 options:
Reflection
Catch Exception
Hope GetADynamicThing() returns what you expect it to return
Number 3 seems to be the targeted usage of dynamic which in COM situations is great. The reason I asked the question originally was in response to doing something like this i.e. using methods some arbitrarily created object. This very much seems like the wrong situation to be using dynamic.
The dynamic type is not meant to be a replacement for System.Object. If you have NO idea what is being returned, using System.Object or a concrete interface in your API is still a better approach than using dynamic, even in C# 4.
Dynamic is very useful if you know, basically, what you are returning. You should treat a member being missing (ie: Foo) as an exceptional case, in which case the exception is a reasonable way of handling this.
The whole point of the dynamic type is to assume member presence.
If you really need to know before you call the method use reflection or better yet create a concrete type the implements an interface that declares Foo(). I would contend that if you need to check if Foo() is a member of a dynamic type, then dynamic is the wrong choice for you. It sounds like you need static type checking.
If your architecture is so open such that you have no idea what is being returned by GetADynamicThing then you should either catch the exception or use reflection somehow. However, in most scenarios, you will have a good idea of what you should be getting and can make some assumptions.
If there is no way to find out right now, I hope they do.
Maintenance nightmare
C# 4.0 introduces dynamic keyword, which will look up at run-time.
Does this mean we'll need awkward reflection no more? If does, Can you show up an example of it?
We'll still have Reflection - using 'dynamic' against regular CLR objects will invoke a Reflection-based dispatcher.
So - we'll still have Reflection, but it'll be easier to do.
Here's an example:
// Via 'dynamic'
dynamic dx = GetSomeCLRObject();
dx.DoSomething();
dx.SomeMember = 2;
// Via Reflection
object x = GetSomeCLRObject();
Type xt = x.GetType();
MemberInfo DoSomethingMethod = xt.GetMethod("DoSomething");
DoSomethingMethod.Invoke(x, null);
PropertyInfo SomeMemberProperty = xt.GetProperty("SomeMember");
SomeMemberProperty.SetValue(x, 2);
I don't know about you, but I like the former. =)
In both these cases, I get no compile-time checking, no Intellisense, no IDE support - but the former case is much more expressive than the latter.
Dynamic dispatch is only one possible use of Reflection. There are many good reasons to interrogate a class for its structure, get information about that structure and visualize in some form or act on it in some way without ever dynamically accessing members. Reflection is here to stay. :)
If you want examples of the dynamic keyword, here is a video from PDC of the man himself talking about it (and other stuff C# 4.0 related).
Dynamic will go a long way to solving problems with methods known only by name, where that name is known and fixed at compile time - but of course, such methods could also be expressed as interfaces if you control the types.
There are cases where dynamic would not help at all:
where the method name isn't known at compile time (i.e. it is loaded from config / user input)
object creation
maybe some generics scenarios
The biggest uses I see for dynamic are:
COM interop (obviously)
generic operator support
duck typing where there is no common interface
DLR interop (see comments)
But it definitely doesn't solve every reflection woe.
I'm just wondering how other developers tackle this issue of getting 2 or 3 answers from a method.
1) return a object[]
2) return a custom class
3) use an out or ref keyword on multiple variables
4) write or borrow (F#) a simple Tuple<> generic class
http://slideguitarist.blogspot.com/2008/02/whats-f-tuple.html
I'm working on some code now that does data refreshes. From the method that does the refresh I would like to pass back (1) Refresh Start Time and (2) Refresh End Time.
At a later date I may want to pass back a third value.
Thoughts? Any good practices from open source .NET projects on this topic?
It entirely depends on what the results are. If they are related to one another, I'd usually create a custom class.
If they're not really related, I'd either use an out parameter or split the method up. If a method wants to return three unrelated items, it's probably doing too much. The exception to this is when you're talking across a web-service boundary or something else where a "purer" API may be too chatty.
For two, usually 4)
More than that, 2)
Your question points to the possibility that you'll be returning more data in the future, so I would recommend implementing your own class to contain the data.
What this means is that your method signature will remain the same even if the inner representation of the object you're passing around changes to accommodate more data. It's also good practice for readability and encapsulation reasons.
Code Architeture wise i'd always go with a Custom Class when needing somewhat a specific amount of variables changed. Why? Simply because a Class is actually a "blueprint" of an often used data type, creating your own data type, which it in this case is, will help you getting a good structure and helping others programme for your interface.
Personally, I hate out/ref params, so I'd rather not use that approach. Also, most of the time, if you need to return more than one result, you are probably doing something wrong.
If it really is unavoidable, you will probably be happiest in the long run writing a custom class. Returning an array is tempting as it is easy and effective in the short teerm, but using a class gives you the option of changing the return type in the future without having to worry to much about causing problems down stream. Imagine the potential for a debugging nightmare if someone swaps the order of two elements in the array that is returned....
I use out if it's only 1 or 2 additional variables (for example, a function returns a bool that is the actual important result, but also a long as an out parameter to return how long the function ran, for logging purposes).
For anything more complicated, i usually create a custom struct/class.
I think the most common way a C# programmer would do this would be to wrap the items you want to return in a separate class. This would provide you with the most flexibility going forward, IMHO.
It depends. For an internal only API, I'll usually choose the easiest option. Generally that's out.
For a public API, a custom class usually makes more sense - but if it's something fairly primitive, or the natural result of the function is a boolean (like *.TryParse) I'll stick with an out param. You can do a custom class with an implicit cast to bool as well, but that's usually just weird.
For your particular situation, a simple immutable DateRange class seems most appropriate to me. You can easily add that new value without disturbing existing users.
If you're wanting to send back the refresh start and end times, that suggests a possible class or struct, perhaps called DataRefreshResults. If your possible third value is also related to the refresh, then it could be added. Remember, a struct is always passed by value, so it's allocated on the heap does not need to be garbage-collected.
Some people use KeyValuePair for two values. It's not great though because it just labels the two things as Key and Value. Not very descriptive. Also it would seriously benefit from having this added:
public static class KeyValuePair
{
public static KeyValuePair<K, V> Make(K k, V v)
{
return new KeyValuePair<K, V>(k, v);
}
}
Saves you from having to specify the types when you create one. Generic methods can infer types, generic class constructors can't.
For your scenario you may want to define generic Range{T} class (with checks for the range validity).
If method is private, then I usually use tuples from my helper library. Public or protected methods generally always deserve separate.
Return a custom type, but don't use a class, use a struct - no memory allocation/garbage collection overhead means no downsides.
If 2, a Pair.
If more than 2 a class.
Another solution is to return a dictionary of named object references. To me, this is pretty equivalent to using a custom return class, but without the clutter. (And using RTTI and reflection it is just as typesafe as any other solution, albeit dynamically so.)
It depends on the type and meaning of the results, as well as whether the method is private or not.
For private methods, I usually just use a Tuple, from my class library.
For public/protected/internal methods (ie. not private), I use either out parameter or a custom class.
For instance, if I'm implementing the TryXYZ pattern, where you have an XYZ method that throws an exception on failure and a TryXYZ method that returns Boolean, TryXYZ will use an out parameter.
If the results are sequence-oriented (ie. return 3 customers that should be processed) then I will typically return some kind of collection.
Other than that I usually just use a custom class.
If a method outputs two to three related value, I would group them in a type. If the values are unrelated, the method is most likely doing way too much and I would refactor it into a number of simpler methods.