Search Results

Search found 1026 results on 42 pages for 'func'.

Page 1/42 | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • C#/.NET Little Wonders: The Generic Func Delegates

    - by James Michael Hare
    Once again, in this series of posts I look at the parts of the .NET Framework that may seem trivial, but can help improve your code by making it easier to write and maintain. The index of all my past little wonders posts can be found here. Back in one of my three original “Little Wonders” Trilogy of posts, I had listed generic delegates as one of the Little Wonders of .NET.  Later, someone posted a comment saying said that they would love more detail on the generic delegates and their uses, since my original entry just scratched the surface of them. Last week, I began our look at some of the handy generic delegates built into .NET with a description of delegates in general, and the Action family of delegates.  For this week, I’ll launch into a look at the Func family of generic delegates and how they can be used to support generic, reusable algorithms and classes. Quick Delegate Recap Delegates are similar to function pointers in C++ in that they allow you to store a reference to a method.  They can store references to either static or instance methods, and can actually be used to chain several methods together in one delegate. Delegates are very type-safe and can be satisfied with any standard method, anonymous method, or a lambda expression.  They can also be null as well (refers to no method), so care should be taken to make sure that the delegate is not null before you invoke it. Delegates are defined using the keyword delegate, where the delegate’s type name is placed where you would typically place the method name: 1: // This delegate matches any method that takes string, returns nothing 2: public delegate void Log(string message); This delegate defines a delegate type named Log that can be used to store references to any method(s) that satisfies its signature (whether instance, static, lambda expression, etc.). Delegate instances then can be assigned zero (null) or more methods using the operator = which replaces the existing delegate chain, or by using the operator += which adds a method to the end of a delegate chain: 1: // creates a delegate instance named currentLogger defaulted to Console.WriteLine (static method) 2: Log currentLogger = Console.Out.WriteLine; 3:  4: // invokes the delegate, which writes to the console out 5: currentLogger("Hi Standard Out!"); 6:  7: // append a delegate to Console.Error.WriteLine to go to std error 8: currentLogger += Console.Error.WriteLine; 9:  10: // invokes the delegate chain and writes message to std out and std err 11: currentLogger("Hi Standard Out and Error!"); While delegates give us a lot of power, it can be cumbersome to re-create fairly standard delegate definitions repeatedly, for this purpose the generic delegates were introduced in various stages in .NET.  These support various method types with particular signatures. Note: a caveat with generic delegates is that while they can support multiple parameters, they do not match methods that contains ref or out parameters. If you want to a delegate to represent methods that takes ref or out parameters, you will need to create a custom delegate. We’ve got the Func… delegates Just like it’s cousin, the Action delegate family, the Func delegate family gives us a lot of power to use generic delegates to make classes and algorithms more generic.  Using them keeps us from having to define a new delegate type when need to make a class or algorithm generic. Remember that the point of the Action delegate family was to be able to perform an “action” on an item, with no return results.  Thus Action delegates can be used to represent most methods that take 0 to 16 arguments but return void.  You can assign a method The Func delegate family was introduced in .NET 3.5 with the advent of LINQ, and gives us the power to define a function that can be called on 0 to 16 arguments and returns a result.  Thus, the main difference between Action and Func, from a delegate perspective, is that Actions return nothing, but Funcs return a result. The Func family of delegates have signatures as follows: Func<TResult> – matches a method that takes no arguments, and returns value of type TResult. Func<T, TResult> – matches a method that takes an argument of type T, and returns value of type TResult. Func<T1, T2, TResult> – matches a method that takes arguments of type T1 and T2, and returns value of type TResult. Func<T1, T2, …, TResult> – and so on up to 16 arguments, and returns value of type TResult. These are handy because they quickly allow you to be able to specify that a method or class you design will perform a function to produce a result as long as the method you specify meets the signature. For example, let’s say you were designing a generic aggregator, and you wanted to allow the user to define how the values will be aggregated into the result (i.e. Sum, Min, Max, etc…).  To do this, we would ask the user of our class to pass in a method that would take the current total, the next value, and produce a new total.  A class like this could look like: 1: public sealed class Aggregator<TValue, TResult> 2: { 3: // holds method that takes previous result, combines with next value, creates new result 4: private Func<TResult, TValue, TResult> _aggregationMethod; 5:  6: // gets or sets the current result of aggregation 7: public TResult Result { get; private set; } 8:  9: // construct the aggregator given the method to use to aggregate values 10: public Aggregator(Func<TResult, TValue, TResult> aggregationMethod = null) 11: { 12: if (aggregationMethod == null) throw new ArgumentNullException("aggregationMethod"); 13:  14: _aggregationMethod = aggregationMethod; 15: } 16:  17: // method to add next value 18: public void Aggregate(TValue nextValue) 19: { 20: // performs the aggregation method function on the current result and next and sets to current result 21: Result = _aggregationMethod(Result, nextValue); 22: } 23: } Of course, LINQ already has an Aggregate extension method, but that works on a sequence of IEnumerable<T>, whereas this is designed to work more with aggregating single results over time (such as keeping track of a max response time for a service). We could then use this generic aggregator to find the sum of a series of values over time, or the max of a series of values over time (among other things): 1: // creates an aggregator that adds the next to the total to sum the values 2: var sumAggregator = new Aggregator<int, int>((total, next) => total + next); 3:  4: // creates an aggregator (using static method) that returns the max of previous result and next 5: var maxAggregator = new Aggregator<int, int>(Math.Max); So, if we were timing the response time of a web method every time it was called, we could pass that response time to both of these aggregators to get an idea of the total time spent in that web method, and the max time spent in any one call to the web method: 1: // total will be 13 and max 13 2: int responseTime = 13; 3: sumAggregator.Aggregate(responseTime); 4: maxAggregator.Aggregate(responseTime); 5:  6: // total will be 20 and max still 13 7: responseTime = 7; 8: sumAggregator.Aggregate(responseTime); 9: maxAggregator.Aggregate(responseTime); 10:  11: // total will be 40 and max now 20 12: responseTime = 20; 13: sumAggregator.Aggregate(responseTime); 14: maxAggregator.Aggregate(responseTime); The Func delegate family is useful for making generic algorithms and classes, and in particular allows the caller of the method or user of the class to specify a function to be performed in order to generate a result. What is the result of a Func delegate chain? If you remember, we said earlier that you can assign multiple methods to a delegate by using the += operator to chain them.  So how does this affect delegates such as Func that return a value, when applied to something like the code below? 1: Func<int, int, int> combo = null; 2:  3: // What if we wanted to aggregate the sum and max together? 4: combo += (total, next) => total + next; 5: combo += Math.Max; 6:  7: // what is the result? 8: var comboAggregator = new Aggregator<int, int>(combo); Well, in .NET if you chain multiple methods in a delegate, they will all get invoked, but the result of the delegate is the result of the last method invoked in the chain.  Thus, this aggregator would always result in the Math.Max() result.  The other chained method (the sum) gets executed first, but it’s result is thrown away: 1: // result is 13 2: int responseTime = 13; 3: comboAggregator.Aggregate(responseTime); 4:  5: // result is still 13 6: responseTime = 7; 7: comboAggregator.Aggregate(responseTime); 8:  9: // result is now 20 10: responseTime = 20; 11: comboAggregator.Aggregate(responseTime); So remember, you can chain multiple Func (or other delegates that return values) together, but if you do so you will only get the last executed result. Func delegates and co-variance/contra-variance in .NET 4.0 Just like the Action delegate, as of .NET 4.0, the Func delegate family is contra-variant on its arguments.  In addition, it is co-variant on its return type.  To support this, in .NET 4.0 the signatures of the Func delegates changed to: Func<out TResult> – matches a method that takes no arguments, and returns value of type TResult (or a more derived type). Func<in T, out TResult> – matches a method that takes an argument of type T (or a less derived type), and returns value of type TResult(or a more derived type). Func<in T1, in T2, out TResult> – matches a method that takes arguments of type T1 and T2 (or less derived types), and returns value of type TResult (or a more derived type). Func<in T1, in T2, …, out TResult> – and so on up to 16 arguments, and returns value of type TResult (or a more derived type). Notice the addition of the in and out keywords before each of the generic type placeholders.  As we saw last week, the in keyword is used to specify that a generic type can be contra-variant -- it can match the given type or a type that is less derived.  However, the out keyword, is used to specify that a generic type can be co-variant -- it can match the given type or a type that is more derived. On contra-variance, if you are saying you need an function that will accept a string, you can just as easily give it an function that accepts an object.  In other words, if you say “give me an function that will process dogs”, I could pass you a method that will process any animal, because all dogs are animals.  On the co-variance side, if you are saying you need a function that returns an object, you can just as easily pass it a function that returns a string because any string returned from the given method can be accepted by a delegate expecting an object result, since string is more derived.  Once again, in other words, if you say “give me a method that creates an animal”, I can pass you a method that will create a dog, because all dogs are animals. It really all makes sense, you can pass a more specific thing to a less specific parameter, and you can return a more specific thing as a less specific result.  In other words, pay attention to the direction the item travels (parameters go in, results come out).  Keeping that in mind, you can always pass more specific things in and return more specific things out. For example, in the code below, we have a method that takes a Func<object> to generate an object, but we can pass it a Func<string> because the return type of object can obviously accept a return value of string as well: 1: // since Func<object> is co-variant, this will access Func<string>, etc... 2: public static string Sequence(int count, Func<object> generator) 3: { 4: var builder = new StringBuilder(); 5:  6: for (int i=0; i<count; i++) 7: { 8: object value = generator(); 9: builder.Append(value); 10: } 11:  12: return builder.ToString(); 13: } Even though the method above takes a Func<object>, we can pass a Func<string> because the TResult type placeholder is co-variant and accepts types that are more derived as well: 1: // delegate that's typed to return string. 2: Func<string> stringGenerator = () => DateTime.Now.ToString(); 3:  4: // This will work in .NET 4.0, but not in previous versions 5: Sequence(100, stringGenerator); Previous versions of .NET implemented some forms of co-variance and contra-variance before, but .NET 4.0 goes one step further and allows you to pass or assign an Func<A, BResult> to a Func<Y, ZResult> as long as A is less derived (or same) as Y, and BResult is more derived (or same) as ZResult. Sidebar: The Func and the Predicate A method that takes one argument and returns a bool is generally thought of as a predicate.  Predicates are used to examine an item and determine whether that item satisfies a particular condition.  Predicates are typically unary, but you may also have binary and other predicates as well. Predicates are often used to filter results, such as in the LINQ Where() extension method: 1: var numbers = new[] { 1, 2, 4, 13, 8, 10, 27 }; 2:  3: // call Where() using a predicate which determines if the number is even 4: var evens = numbers.Where(num => num % 2 == 0); As of .NET 3.5, predicates are typically represented as Func<T, bool> where T is the type of the item to examine.  Previous to .NET 3.5, there was a Predicate<T> type that tended to be used (which we’ll discuss next week) and is still supported, but most developers recommend using Func<T, bool> now, as it prevents confusion with overloads that accept unary predicates and binary predicates, etc.: 1: // this seems more confusing as an overload set, because of Predicate vs Func 2: public static SomeMethod(Predicate<int> unaryPredicate) { } 3: public static SomeMethod(Func<int, int, bool> binaryPredicate) { } 4:  5: // this seems more consistent as an overload set, since just uses Func 6: public static SomeMethod(Func<int, bool> unaryPredicate) { } 7: public static SomeMethod(Func<int, int, bool> binaryPredicate) { } Also, even though Predicate<T> and Func<T, bool> match the same signatures, they are separate types!  Thus you cannot assign a Predicate<T> instance to a Func<T, bool> instance and vice versa: 1: // the same method, lambda expression, etc can be assigned to both 2: Predicate<int> isEven = i => (i % 2) == 0; 3: Func<int, bool> alsoIsEven = i => (i % 2) == 0; 4:  5: // but the delegate instances cannot be directly assigned, strongly typed! 6: // ERROR: cannot convert type... 7: isEven = alsoIsEven; 8:  9: // however, you can assign by wrapping in a new instance: 10: isEven = new Predicate<int>(alsoIsEven); 11: alsoIsEven = new Func<int, bool>(isEven); So, the general advice that seems to come from most developers is that Predicate<T> is still supported, but we should use Func<T, bool> for consistency in .NET 3.5 and above. Sidebar: Func as a Generator for Unit Testing One area of difficulty in unit testing can be unit testing code that is based on time of day.  We’d still want to unit test our code to make sure the logic is accurate, but we don’t want the results of our unit tests to be dependent on the time they are run. One way (of many) around this is to create an internal generator that will produce the “current” time of day.  This would default to returning result from DateTime.Now (or some other method), but we could inject specific times for our unit testing.  Generators are typically methods that return (generate) a value for use in a class/method. For example, say we are creating a CacheItem<T> class that represents an item in the cache, and we want to make sure the item shows as expired if the age is more than 30 seconds.  Such a class could look like: 1: // responsible for maintaining an item of type T in the cache 2: public sealed class CacheItem<T> 3: { 4: // helper method that returns the current time 5: private static Func<DateTime> _timeGenerator = () => DateTime.Now; 6:  7: // allows internal access to the time generator 8: internal static Func<DateTime> TimeGenerator 9: { 10: get { return _timeGenerator; } 11: set { _timeGenerator = value; } 12: } 13:  14: // time the item was cached 15: public DateTime CachedTime { get; private set; } 16:  17: // the item cached 18: public T Value { get; private set; } 19:  20: // item is expired if older than 30 seconds 21: public bool IsExpired 22: { 23: get { return _timeGenerator() - CachedTime > TimeSpan.FromSeconds(30.0); } 24: } 25:  26: // creates the new cached item, setting cached time to "current" time 27: public CacheItem(T value) 28: { 29: Value = value; 30: CachedTime = _timeGenerator(); 31: } 32: } Then, we can use this construct to unit test our CacheItem<T> without any time dependencies: 1: var baseTime = DateTime.Now; 2:  3: // start with current time stored above (so doesn't drift) 4: CacheItem<int>.TimeGenerator = () => baseTime; 5:  6: var target = new CacheItem<int>(13); 7:  8: // now add 15 seconds, should still be non-expired 9: CacheItem<int>.TimeGenerator = () => baseTime.AddSeconds(15); 10:  11: Assert.IsFalse(target.IsExpired); 12:  13: // now add 31 seconds, should now be expired 14: CacheItem<int>.TimeGenerator = () => baseTime.AddSeconds(31); 15:  16: Assert.IsTrue(target.IsExpired); Now we can unit test for 1 second before, 1 second after, 1 millisecond before, 1 day after, etc.  Func delegates can be a handy tool for this type of value generation to support more testable code.  Summary Generic delegates give us a lot of power to make truly generic algorithms and classes.  The Func family of delegates is a great way to be able to specify functions to calculate a result based on 0-16 arguments.  Stay tuned in the weeks that follow for other generic delegates in the .NET Framework!   Tweet Technorati Tags: .NET, C#, CSharp, Little Wonders, Generics, Func, Delegates

    Read the article

  • Deciding between obj->func() and func(obj)

    - by GSto
    I was thinking about this when I was starting to set up some code for a new project: are there any rules of thumb for when a method should be part of an object, and when it should be a stand alone function that takes an object as a parameter? EDIT: as pointed out in a comment, this can depend on language. I was working in C++ when it came to mind, though I'm this is an issue across a number of languages (and would still love to see answers that pertain to them).

    Read the article

  • C# ambiguity in Func + extension methods + lambdas

    - by Hobbes
    I've been trying to make my way through this article: http://blogs.msdn.com/wesdyer/archive/2008/01/11/the-marvels-of-monads.aspx ... And something on page 1 made me uncomfortable. In particular, I was trying to wrap my head around the Compose<() function, and I wrote an example for myself. Consider the following two Func's: Func<double, double> addTenth = x => x + 0.10; Func<double, string> toPercentString = x => (x * 100.0).ToString() + "%"; No problem! It's easy to understand what these two do. Now, following the example from the article, you can write a generic extension method to compose these functions, like so: public static class ExtensionMethods { public static Func<TInput, TLastOutput> Compose<TInput, TFirstOutput, TLastOutput>( this Func<TFirstOutput, TLastOutput> toPercentString, Func<TInput, TFirstOutput> addTenth) { return input => toPercentString(addTenth(input)); } } Fine. So now you can say: string x = toPercentString.Compose<double, double, string>(addTenth)(0.4); And you get the string "50%" So far, so good. But there's something ambiguous here. Let's say you write another extension method, so now you have two functions: public static class ExtensionMethods { public static Func<TInput, TLastOutput> Compose<TInput, TFirstOutput, TLastOutput>( this Func<TFirstOutput, TLastOutput> toPercentString, Func<TInput, TFirstOutput> addTenth) { return input => toPercentString(addTenth(input)); } public static Func<double, string> Compose<TInput, TFirstOutput, TLastOutput>(this Func<double, string> toPercentString, Func<double, double> addTenth) { return input => toPercentString(addTenth(input + 99999)); } } Herein is the ambiguity. Don't these two function have overlapping signatures? Yes. Does this even compile? Yes. Which one get's called? The second one (which clearly gives you the "wrong" result) gets called. If you comment out either function, it still compiles, but you get different results. It seems like nitpicking, but there's something that deeply offends my sensibilities here, and I can't put my finger on it. Does it have to do with extension methods? Does it have to do with lambdas? Or does it have to do with how Func< allows you to parameterize the return type? I'm not sure. I'm guessing that this is all addressed somewhere in the spec, but I don't even know what to Google to find this. Help!

    Read the article

  • Func<sometype,bool> to Func<T,bool>

    - by user175528
    If i have: public static Func<SomeType, bool> GetQuery() { return a => a.Foo=="Bar"; } and a generic version public static Func<T, bool> GetQuery<T>() { return (Func<T,bool>)GetQuery(); } how can I do the case? The only way I have found so far is to try and combine it with a mock function: Func<T, bool> q=a => true; return (Func<T, bool>)Delegate.Combine(GetQuery(), q); I know how to do that with Expression.Lambda, but I need to work with plain functions, not expression trees

    Read the article

  • Example of a Good Func Spec?

    - by Alex
    Hey, I'm writing my func spec, and I was wondering if there are any good samples of a complete and well-written func spec? Like "This is a standard You're supposed to aspire to" type of spec. I know that Joel has a skeleteon of a func spec on his website, but I am looking for something more complete because I'm not of the appropriate amount of detail, formatting, etc. Thanks, Alex

    Read the article

  • Func Delegate in C#

    - by Jalpesh P. Vadgama
    We already know about delegates in C# and I have previously posted about basics of delegates in C#. Following are posts about basic of delegates I have written. Delegates in C# Multicast Delegates in C# In this post we are going to learn about Func Delegates in C#. As per MSDN following is a definition. “Encapsulates a method that has one parameter and returns a value of the type specified by the TResult parameter.” Func can handle multiple arguments. The Func delegates is parameterized type. It takes any valid C# type as parameter and you have can multiple parameters and also you have specify the return type as last parameters. Followings are some examples of parameters. Func<int T,out TResult> Func<int T,int T, out Tresult> Now let’s take a string concatenation example for that. I am going to create two func delegate which will going to concate two strings and three string. Following is a code for that. using System; using System.Collections.Generic; namespace FuncExample { class Program { static void Main(string[] args) { Func<string, string, string> concatTwo = (x, y) => string.Format("{0} {1}",x,y); Func<string, string, string, string> concatThree = (x, y, z) => string.Format("{0} {1} {2}", x, y,z); Console.WriteLine(concatTwo("Hello", "Jalpesh")); Console.WriteLine(concatThree("Hello","Jalpesh","Vadgama")); Console.ReadLine(); } } } As you can see in above example, I have create two delegates ‘concatTwo’ and ‘concatThree. The first concat two strings and another concat three strings. If you see the func statements the last parameter is for the out as here its output string so I have written string as last parameter in both statements. Now it’s time to run the example and as expected following is output. That’s it. Hope you like it. Stay tuned for more updates.

    Read the article

  • Get Func-y v2.0

    - by PhubarBaz
    In my last post I talked about using funcs in C# to do async calls in WinForms to free up the main thread for the UI. In that post I demonstrated calling a method and then waiting until the value came back. Today I want to talk about calling a method and then continuing on and handling the results of the async call in a callback.The difference is that in the previous example although the UI would not lock up the user couldn't really do anything while the other thread was working because it was waiting for it to finish. This time I want to allow the user to continue to do other stuff while waiting for the thread to finish.Like before I have a service call I want to make that takes a long time to finish defined in a method called MyServiceCall. We need to define a callback method takes an IAsyncResult parameter.public ServiceCallResult MyServiceCall(int param1)...public int MyCallbackMethod(IAsyncResult ar)...We start the same way by defining a delegate to the service call method using a Func. We need to pass an AsyncCallback object into the BeginInvoke method. This will tell it to call our callback method when MyServiceCall finishes. The second parameter to BeginInvoke is the Func delegate. This will give us access to it in our callback.Func<int, ServiceCallResult> f = MyServiceCall;AsyncCallback callback =   new AsyncCallback(MyCallbackMethod);IAsyncResult async = f.BeginInvoke(23, callback, f); Now let's expand the callback method. The IAsyncResult parameter contains the Func delegate in its AsyncState property. We call EndInvoke on that Func to get the return value.public int MyCallbackMethod(IAsyncResult ar){    Func<int, ServiceCallResult> delegate =        (Func<int, ServiceCallResult>)ar.AsyncState;    ServiceCallResult result = delegate.EndInvoke(ar);}There you have it. Now you don't have to make the user wait for something that isn't critical to the loading of the page.

    Read the article

  • In C: sending func pointers, calling the func with it, playing with EIP, jum_buf and longjmp

    - by Yonatan
    Hello Internet ! I need to make sure i understand some basic stuff first: 1. how do i pass function A as a parameter to function B? 2. how do i call function A from inside B ? now for the big whammy: I'm trying to do something along the lines of this: jmp_buf buf; buf.__jmpbuf[JB_PC] = functionA; longjmp(buf,10); meaning that i want to use longjmp in order to go to a function. how should i do it ? thank you very much internet people ! Yonatan

    Read the article

  • How do i refactor this code by using Action<t> or Func<t> delegates

    - by user330612
    I have a sample program, which needs to execute 3 methods in a particular order. And after executing each method, should do error handling. Now i did this in a normal fashion, w/o using delegates like this. class Program { public static void Main() { MyTest(); } private static bool MyTest() { bool result = true; int m = 2; int temp = 0; try { temp = Function1(m); } catch (Exception e) { Console.WriteLine("Caught exception for function1" + e.Message); result = false; } try { Function2(temp); } catch (Exception e) { Console.WriteLine("Caught exception for function2" + e.Message); result = false; } try { Function3(temp); } catch (Exception e) { Console.WriteLine("Caught exception for function3" + e.Message); result = false; } return result; } public static int Function1(int x) { Console.WriteLine("Sum is calculated"); return x + x; } public static int Function2(int x) { Console.WriteLine("Difference is calculated "); return (x - x); } public static int Function3(int x) { return x * x; } } As you can see, this code looks ugly w/ so many try catch loops, which are all doing the same thing...so i decided that i can use delegates to refactor this code so that Try Catch can be all shoved into one method so that it looks neat. I was looking at some examples online and couldnt figure our if i shud use Action or Func delegates for this. Both look similar but im unable to get a clear idea how to implement this. Any help is gr8ly appreciated. I'm using .NET 4.0, so im allowed to use anonymous methods n lambda expressions also for this Thanks

    Read the article

  • Get Func-y

    - by PhubarBaz
    I was working on a Windows form app and needed a way to call out to a service without blocking the UI. There are a lot of ways to do this but I came up with one that I thought was pretty simple. It utilizes the System.Func<> generic class, which is basically a way to create delegates using generics. It's a lot more compact and simpler than creating delegates for each method you want to call asynchronously. I wanted to get it down to one line of code, but it was a lot simpler to use three lines.In this case I have a MyServiceCall method that takes an integer parameter and returns a ServiceCallResult object.public ServiceCallResult MyServiceCall(int param1)...You start by getting a Func<> object for the method you want to call, in this case MyServiceCall. Then you call BeginInvoke() on the Func passing in the parameter. The two nulls are parameters BeginInvoke expects but can be ignored here. BeginInvoke returns an IAsyncResult object that acts like a handle to the method call. Finally to get the value you call EndInvoke on the Func passing in the IAsyncResult object you got back from BeginInvoke.Func<int, ServiceCallResult> f = MyServiceCall;IAsyncResult async = f.BeginInvoke(23, null, null);ServiceCallResult result = f.EndInvoke(async);Doing it this way fires off a new thread that calls the MyServiceCall() method. This leaves the main application thread free to update the UI while the method call is running so it doesn't become unresponsive.

    Read the article

  • Can you get a Func<T> (or similar) from a MethodInfo object?

    - by Dan Tao
    I realize that, generally speaking, there are performance implications of using reflection. (I myself am not a fan of reflection at all, actually; this is a purely academic question.) Suppose there exists some class that looks like this: public class MyClass { public string GetName() { return "My Name"; } } Bear with me here. I know that if I have an instance of MyClass called x, I can call x.GetName(). Furthermore, I could set a Func<string> variable to x.GetName. Now here's my question. Let's say I don't know the above class is called MyClass; I've got some object, x, but I have no idea what it is. I could check to see if that object has a GetName method by doing this: MethodInfo getName = x.GetType().GetMethod("GetName"); Suppose getName is not null. Then couldn't I furthermore check if getName.ReturnType == typeof(string) and getName.GetParameters().Length == 0, and at this point, wouldn't I be quite certain that the method represented by my getName object could definitely be cast to a Func<string>, somehow? I realize there's a MethodInfo.Invoke, and I also realize I could always create a Func<string> like: Func<string> getNameFunc = () => getName.Invoke(x, null); I guess what I'm asking is if there's any way to go from a MethodInfo object to the actual method it represents, incurring the performance cost of reflection in the process, but after that point being able to call the method directly (via, e.g., a Func<string> or something similar) without a performance penalty. What I'm envisioning might look something like this: // obviously this would throw an exception if GetActualInstanceMethod returned // something that couldn't be cast to a Func<string> Func<string> getNameFunc = (Func<string>)getName.GetActualInstanceMethod(x); (I realize that doesn't exist; I'm wondering if there's anything like it.) If what I'm asking doesn't make sense, or if I'm being unclear, I'll be happy to attempt to clarify.

    Read the article

  • Recursion in the form of a Recursive Func&lt;T, T&gt;

    - by ToStringTheory
    I gotta admit, I am kind of surprised that I didn’t realize I could do this sooner.  I recently had a problem which required a recursive function call to come up with the answer.  After some time messing around with a recursive method, and creating an API that I was not happy with, I was able to create an API that I enjoy, and seems intuitive. Introduction To bring it to a simple example, consider the summation to n: A mathematically identical formula is: In a .NET function, this can be represented by a function: Func<int, int> summation = x => x*(x+1)/2 Calling summation with an input integer will yield the summation to that number: var sum10 = summation(4); //sum10 would be equal to 10 But what if I wanted to get a second level summation…  First some to n, and then use that argument as the input to the same function, to find the second level summation: So as an easy example, calculate the summation to 3, which yields 6.  Then calculate the summation to 6 which yields 21. Represented as a mathematical formula - So what if I wanted to represent this as .NET functions.  I can always do: //using the summation formula from above var sum3 = summation(3); //sets sum3 to 6 var sum3_2 = summation(sum3); //sets sum3 to 21 I could always create a while loop to perform the calculations too: Func<int, int> summation = x => x*(x+1)/2; //for the interests of a smaller example, using shorthand int sumResultTo = 3; int level = 2; while(level-- > 0) { sumResultTo = summation(sumResultTo); } //sumResultTo is equal to 21 now. Or express it as a for-loop, method calls, etc…  I really didn’t like any of the options that I tried.  Then it dawned on me – since I was using a Func<T, T> anyways, why not use the Func’s output from one call as the input as another directly. Some Code So, I decided that I wanted a recursion class.  Something that I would be generic and reusable in case I ever wanted to do something like this again. It is limited to only the Func<T1, T2> level of Func, and T1 must be the same as T2. The first thing in this class is a private field for the function: private readonly Func<T, T> _functionToRecurse; So, I since I want the function to be unchangeable, I have defined it as readonly.  Therefore my constructor looks like: public Recursion(Func<T, T> functionToRecurse) { if (functionToRecurse == null) { throw new ArgumentNullException("functionToRecurse", "The function to recurse can not be null"); } _functionToRecurse = functionToRecurse; } Simple enough.  If you have any questions, feel free to post them in the comments, and I will be sure to answer them. Next, I want enough. If be able to get the result of a function dependent on how many levels of recursion: private Func<T, T> GetXLevel(int level) { if (level < 1) { throw new ArgumentOutOfRangeException("level", level, "The level of recursion must be greater than 0"); } if (level == 1) return _functionToRecurse; return _GetXLevel(level - 1, _functionToRecurse); } So, if you pass in 1 for the level, you get just the Func<T,T> back.  If you say that you want to go deeper down the rabbit hole, it calls a method which accepts the level it is at, and the function which it needs to use to recurse further: private Func<T, T> _GetXLevel(int level, Func<T, T> prevFunc) { if (level == 1) return y => prevFunc(_functionToRecurse(y)); return _GetXLevel(level - 1, y => prevFunc(_functionToRecurse(y))); } That is really all that is needed for this class. If I exposed the GetXLevel function publicly, I could use that to get the function for a level, and pass in the argument..  But I wanted something better.  So, I used the ‘this’ array operator for the class: public Func<T,T> this[int level] { get { if (level < 1) { throw new ArgumentOutOfRangeException("level", level, "The level of recursion must be greater than 0"); } return this.GetXLevel(level); } } So, using the same example above of finding the second recursion of the summation of 3: var summator = new Recursion<int>(x => (x * (x + 1)) / 2); var sum_3_level2 = summator[2](3); //yields 21 You can even find just store the delegate to the second level summation, and use it multiple times: var summator = new Recursion<int>(x => (x * (x + 1)) / 2); var sum_level2 = summator[2]; var sum_3_level2 = sum_level2(3); //yields 21 var sum_4_level2 = sum_level2(4); //yields 55 var sum_5_level2 = sum_level2(5); //yields 120 Full Code Don’t think I was just going to hold off on the full file together and make you do the hard work…  Copy this into a new class file: public class Recursion<T> { private readonly Func<T, T> _functionToRecurse; public Recursion(Func<T, T> functionToRecurse) { if (functionToRecurse == null) { throw new ArgumentNullException("functionToRecurse", "The function to recurse can not be null"); } _functionToRecurse = functionToRecurse; } public Func<T,T> this[int level] { get { if (level < 1) { throw new ArgumentOutOfRangeException("level", level, "The level of recursion must be greater than 0"); } return this.GetXLevel(level); } } private Func<T, T> GetXLevel(int level) { if (level < 1) { throw new ArgumentOutOfRangeException("level", level, "The level of recursion must be greater than 0"); } if (level == 1) return _functionToRecurse; return _GetXLevel(level - 1, _functionToRecurse); } private Func<T, T> _GetXLevel(int level, Func<T, T> prevFunc) { if (level == 1) return y => prevFunc(_functionToRecurse(y)); return _GetXLevel(level - 1, y => prevFunc(_functionToRecurse(y))); } } Conclusion The great thing about this class, is that it can be used with any function with same input/output parameters.  I strived to find an implementation that I found clean and useful, and I finally settled on this.  If you have feedback – good or bad, I would love to hear it!

    Read the article

  • Function like C# properties?

    - by alan2here
    I was directed here from SO as a better stack exchange site for this question. I've been thinking about the neatness and expression of C# properties over functions, although they only currently work where no parameters are used, and wondered. Is is possible, and if so why not, to have a stand alone function like C# property. For example: public class test { private byte n = 4; public test() { func = 2; byte n2 = func; func; } private byte func { get { return n; } set { n = value; } func { n++; } } } edit: Sorry for the vagueness first time round. I'm going to add some info and motivation. The 'n++' here is just a simple example, a placeholder, it's not intended to be representative of the actual code that would be used. I'm also looking at this from the point of view of looking at the property command as is, not in the context of using it for 'get_xyz' and 'set_xyz' member functions, which is certainly useful, but of instead comparing it more abstractly to functions and other programic elements. A 'get' property can be used instead of a function that takes no parameters, and syntactically they are perhaps only aesthetically, but as I see it noticeably nicer. However, properties also add the potential for an extra layer of polymorphism, one that relates to the 'func = 4;' getting, 'int n = func;' setting or 'func;' function like context in which they are used as well as the more common parameter based polymorphism. Potentially allowing for a lot of expression and contextual information reguarding how other would use your functions. As in many places uses and definitions would remain the same, it shouldn't break existing code. private byte func { get { } get bool { } set { } func { } func(bool) { } func(byte, myType) { } // etc... } So a read only function would look like this: private byte func { get { } } A normal function like this: private void func { func { } } A function with parameter polymorphism like this: private byte func { func(bool) { } func(byte, myType) { } } And a function that could return a value, or just compute, depending on the context it is used, that also has more conventional parameter polymorphism as well, like so: private byte func { get { } func(bool) { } func(byte, myType) { } }

    Read the article

  • How can I pass in a params of Expression<Func<T, object>> to a method?

    - by Pure.Krome
    Hi folks, I have the following two methods :- public static IQueryable<T> IncludeAssociations<T>(this IQueryable<T> source, params string[] associations) { ... } public static IQueryable<T> IncludeAssociations<T>(this IQueryable<T> source, params Expression<Func<T, object>>[] expressions) { ... } Now, when I try and pass in a params of Expression<Func<T, object>>[], it always calls the first method (the string[]' and of course, that value isNULL`) Eg. Expression<Func<Order, object>> x1 = x => x.User; Expression<Func<Order, object>> x2 = x => x.User.Passport; var foo = _orderRepo .Find() .IncludeAssociations(new {x1, x2} ) .ToList(); Can anyone see what I've done wrong? Why is it thinking my params are a string? Can I force the type, of the 2x variables?

    Read the article

  • Why is Func<T> ambiguous with Func<IEnumerable<T>>?

    - by Matt Hamilton
    This one's got me flummoxed, so I thought I'd ask here in the hope that a C# guru can explain it to me. Why does this code generate an error? class Program { static void Main(string[] args) { Foo(X); // the error is on this line } static String X() { return "Test"; } static void Foo(Func<IEnumerable<String>> x) { } static void Foo(Func<String> x) { } } The error in question: Error 1 The call is ambiguous between the following methods or properties: 'ConsoleApplication1.Program.Foo(System.Func<System.Collections.Generic.IEnumerable<string>>)' and 'ConsoleApplication1.Program.Foo(System.Func<string>)' C:\Users\mabster\AppData\Local\Temporary Projects\ConsoleApplication1\Program.cs 12 13 ConsoleApplication1 It doesn't matter what type I use - if you replace the "String" declarations with "int" in that code you'll get the same sort of error. It's like the compiler can't tell the difference between Func<T> and Func<IEnumerable<T>>. Can someone shed some light on this?

    Read the article

  • Logitech Media Elite Func button

    - by Noam Gal
    I have the aforementioned keyboard, and occasionally the "Func" key will get unpressed. It gets especially annoying when I try to rename a file, and start winword by accident, or try to refresh a page, and nothing happens (It's the undo - no effect inside a browser usually). I know I can rebind those keys to just do nothing, but I just wanted to know why does the func mode changes by itself? Can it be something with power management/screen saver?

    Read the article

  • LINQ Expression<Func<T, bool>> equavalent of .Contains()

    - by BK
    Has anybody got an idea of how to create a .Contains(string) function using Linq Expressions, or even create a predicate to accomplish this public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2) { var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>()); return Expression.Lambda<Func<T, bool>> (Expression.OrElse(expr1.Body, invokedExpr), expr1.Parameters); } Something simular to this would be ideal?

    Read the article

  • Passing a template func. as a func. ptr to an overloaded func. - is there a way to compile this code

    - by LoudNPossiblyRight
    Just a general c++ curiosity: This code below shouldn't compile because it's impossible to know which to instantiate: temp(const int&) or temp(const string&) when calling func(temp) - this part i know. What i would like to know is if there is anything i can do to the line marked PASSINGLINE to get the compiler to deduce that i want FPTR1 called and not FPTR2 ? #include<iostream> using std::cout; using std::endl; /*FPTR1*/ void func(void(*fptr)(const int&)){ fptr(1001001);} /*FPTR2*/ void func(void(*fptr)(const string&)){ fptr("1001001"); } template <typename T> void temp(const T &t){ cout << t << endl; } int main(){ /*PASSINGLINE*/ func(temp); return 0; } Thank you.

    Read the article

  • Recursion with Func

    - by David in Dakota
    Is it possible to do recursion with an Func delegate? I have the following, which doesn't compile because the name of the Func isn't in scope... Func<long, long, List<long>, IEnumerable<long>> GeneratePrimesRecursively = (number, upperBound, primeFactors) => { if (upperBound > number) { return new List<long>(); } else { if (!primeFactors.Any(factor => number % factor == 0)) primeFactors.Add(number); return GeneratePrimesRecursively(++number, upperBound, primeFactors); // breaks here. } };

    Read the article

  • Calling a static Func from a static class using reflection

    - by ChrisO
    Given the static class: public static class Converters { public static Func<Int64, string> Gold = c => String.Format("{0}g {1}s {2}c", c/10000, c/100%100, c%100); } I am receiving the Func name from a database as a string (regEx.Converter). How can I invoke the Gold Func using reflection? Here is what I have so far: var converter = typeof(Converters).GetMember(regEx.Converter); if (converter.Count() != 0) { //throw new ConverterNotFoundException; } matchedValue = converter.Invoke(null, new object[]{matchedValue}) as string;

    Read the article

  • In few words, what can be said about Func<>

    - by Richard77
    Hello, I've been seing Func< for sometime now, and I've manage to avoid it (for now). But, now it looks like I can't dodge it forever. For instance, I tried Dynamic Linq, but almost everything was in terms of Func<. I've tried one of my book (C# 2008/Deitel&Deitel) and also MSDN but I'm not getting it yet. They all jump straight in the subject. What can be said (in few words) about Func< Can I get some links on the web that can get me started on that matter? Thanks for helping

    Read the article

  • C# Func delegate with params type

    - by Sarah Vessels
    How, in C#, do I have a Func parameter representing a method with this signature? XmlNode createSection(XmlDocument doc, params XmlNode[] childNodes) I tried having a parameter of type Func<XmlDocument, params XmlNode[], XmlNode> but, ooh, ReSharper/Visual Studio 2008 go crazy highlighting that in red.

    Read the article

1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >