How to stub a method with out parameter using custom delegate? - c#

I am trying to stub a method that has an out paramteter using RhinoMock's Do method, but I keep getting the message cannot resolve symbol outParam. Here's the stubbing part:
private static void FakeClientsLoading(MyClass fakeClass, IEnumerable<string> clientsToLoad)
{
fakeClass.Stub(
x =>
x.LoadClientsFromDb(Arg<string>.Is.Anything,
out Arg<object>.Out(null).Dummy))
.Do(
new LoadClientsFromDbAction(
(someString, out outParam ) =>
TestHelper.LoadClients(someString, clientsToLoad)));
}
And here is my custom delegate declaration:
public delegate void LoadClientsFromDbAction(string s, out object outParam);
What I'd like to achieve is to run the test helper method whenever LoadClientsFromDb is invoked. From my understanding outParam should be mapped to whatever is passed as the out parameter to the called method, but it doesn't seem to work this way.

It seems that I have finally found the answer to my question. It turns out that, quoting section 26.3.1 from this link:
Specifically, a delegate type D is compatible with an anonymous method
or lambda-expression L provided:
If L is a lambda expression that has an implicitly typed parameter list, D has no ref or out parameters.
This means that you need an explicitly typed parameter list in order to create a lambda with an out parameter.
That's not all, though. It is still necessary to assign a value to the out parameter upon exiting the anonymous method.
The final and working code:
private static void FakeClientsLoading(MyClass fakeClass, IEnumerable<string> clientsToLoad)
{
fakeClass.Stub(
x =>
x.LoadClientsFromDb(Arg<string>.Is.Anything,
out Arg<object>.Out(null).Dummy))
.Do(
new LoadClientsFromDbAction(
(string someString, out object outParam) =>
{
outParam = null;
TestHelper.LoadClients(someString, clientsToLoad);
}
));
}

Related

Why Lambda expression parameter appears in method parameter list?

I am trying to get the parameters list of a class method using Roslyn and noticed a strange behavior that Roslyn considers and returns a Lambda parameter used inside the body of the method as as one of the parameters of the method, which cause an error in my code. Why does Roslyn consider a lambda parameter as of the method's parameters?
Here is the code:
var paramDeclaratons = memmeth.DescendantNodes().OfType<ParameterSyntax>();
foreach (var mempara in paramDeclaratons)
{
String paramType = mempara.Type.ToFullString().Trim(); //Here it crashes with System.NullReferenceException because Lambda returns no type!
The code which is parsed:
public void Method1(RequestId requestId)
{
...
var packetsToKeep = this.queuedPackets.Where(p => p.RequestId != requestId)
p is returned as one of the parameters of Method1 with no type
Assuming memmeth is a MethodDeclarationSyntax, then what you want is to access its ParameterList.Parameters:
var paramDeclaratons = memmeth.ParameterList.Parameters;

Create generic Func from reflection

I've specified type in a variable: Type hiddenType. I need to create a Func<T> delegate where T is of type specified in mentioned variable and assign an method:
var funcType = typeof(Func<>).MakeGenericType(hiddenType);
Func<object> funcImplementation = () => GetInstance(hiddenType);
var myFunc= Delegate.CreateDelegate(funcType , valueGenerator.Method);
It doesn't works - because funcImplementation is returns object instead of desired. At runtime, it will surely be an instance of type specified in hiddenType.
GetInstance returns object and signaure cannot be changed.
You can solve this by building an expression tree manually, and inserting a cast to hiddenType. This is allowed when you construct an expression tree.
var typeConst = Expression.Constant(hiddenType);
MethodInfo getInst = ... // <<== Use reflection here to get GetInstance info
var callGetInst = Expression.Call(getInst, typeConst);
var cast = Expression.Convert(callGetInst, hiddenType);
var del = Expression.Lambda(cast).Compile();
Note: the above code assumes that GetInstance is static. If it is not static, change the way you construct callGetInst to pass the object on which the method is invoked.
Instead of using a Type, you could consider using a generic wrapper, if it's not possible for you to change the GetInstance signature:
private Func<THidden> GetTypedInstance<THidden>()
{
return () => (THidden)GetInstance(typeof(THidden));
}
Then you can just call it with
GetTypedInstance<SomeClass>();
instead of
GetInstance(typeof(SomeClass));

C# syntax, assign delegate to a class, and call later

I have a bit of confusion with this C# syntax.
I'm trying to assign an arbitrary delegate to a class.
I have a delegates defined as
delegate string stringCB(string s);
delegate int intCB(int i);
I have a class
class run_by_name {
public string name {get;set;}
public Delegate method {get;set;}
};
And I'm trying to instantiate it
run_by_name myfuc = new run_by_name(){
name = "my name",
method = new stringCB(string s) {
return " testing " + s;
};
};
I'm really not clear how to assign to a delegate when there's a return type. Also I'm not sure how to call that method later on syntactically.
Why I'm doing this? Well I'm just writing some code that follows a pattern I use in JS a lot for event handling, I'm just making an "object" I can assign arbitrary functions to for a generic event handler that's created rather than defined. (important)
Also, alternatives to using delegates are welcome. :)
EDIT: How I might use it later
I don't have that written yet but Im pretty sure I'll be doing this.
List<run_by_name> callbacks = new List<run_by_name>();
/* lets say this is initialized and filled at this point */
public object FindAndRunCallback(string Name, object input) {
foreach(var cb in callbacks) {
if( cb.name == Name )
return cb.method(input);
}
return null;
}
Here's the syntax you need to get your current code working:
method = new stringCB((string s) => {
return " testing " + s;
})
Or, using lambda expressions:
method = new stringCB(s =>" testing " + s)
You could later invoke the method like so:
string result = (string) myfuc.method.DynamicInvoke("hello");
Without knowing more about your use case, it's hard to recommend other approaches, but I'd recommend at least looking into the following:
Events: Your description sounds very close to the common pattern for events and event handlers in C#. Your event defines the delegate type that is used to handle it, and code elsewhere can subscribe to that event with methods that match that delegate type. By convention, people usually pass a sender object as the first parameter, and some strongly-typed EventArgs so that subscribers don't have to guess at what data is going to be available when the event fires.
Func<> and Action<> variants: As C# has evolved into a more functional language, programmers have trended away from using custom delegate types, and toward using the provided variants of Func<> and Action<>. Since the arguments are strongly-typed still, you get most of the advantages of a compiled language, but use a little "duck typing" for the actual function you pass around.
For example, you could give your class a generic type based on what types you expect your delegate to deal with:
class run_by_name<T> {
public string name {get;set;}
public Func<T, T> method {get;set;}
};
Then use it:
var myfuc = new run_by_name<string>{
name = "my name",
method = s =>" testing " + s
};
string result = myfuc.method("hello");
dynamic: This keyword allows you to late-bind actions on any object. You lose the advantages of a compiled language, but it improves interoperability with more dynamic languages immensely. For example, an object can be created via JSON, and you can access the properties on it without declaring a special type for that object, just like you can in Javascript.
For example, if you changed your method declaration to this:
public dynamic method {get;set;}
Then you could simply say:
string result = myfuc.method("hello");
You have seceral choices. the strinCB constructor expects a method, that takes a string parameter and returns a string. If you have an existing method, you can pass it's name to the constructor, or you can create an anonymous method wither by delegate syntax like this:
method = new stringCB(delegate(string s)
{
return " testing " + s;
})
Or using a lambda expression:
method = new stringCB(s =>
{
return " testing " + s;
})
Then you can call it like this: myfuc.method.DynamicInvoke(YourParameter);
Normally, calling a delegate's method is pretty easy like this:
Func<int, int, int> sum = (x, y) => x + y;
Console.WriteLine(sum(2,3)); // with the name of delegate
Console.WriteLine(sum.Invoke(2,3)); // or using Invoke method
But in this case, you need to use DynamicInvoke because the type of your property is Delegate.
Apart from that .NET Framework has some useful built-in delegate types, such as Func,Action and Predicate etc. You can use them instead of creating your own delegate as long as they satisfy your needs. For example in this case you can use a Func<string,string> instead of stringCB.

Assign a function delegate that returns an anonymous type to a variable

The code below is valid:
IEnumerable<SomeThing> things = ...;
// map type SomeThing to a new anonymous type, resulting in a strongly typed
// sequence based on an anon type
var newList = things.Select(item =>
{
return new
{
ID = item.ID,
DateUpdatedOrCreated = ((DateTime)(item.DateUpdated ??
item.DateCreated)).ToShortDateString(),
Total = item.Part1 + item.Part2
};
});
newList now appears in Visual Studio as IEnumerable<'a> and is strongly typed with the anonymous type created in the function. That is so cool.
What I can't seem to do is figure out a way to assign just the lambda expression (and not the enumeration) to an implicitly typed variable. Even though the compiler has no problem with the anonymous type in the context above, if I try (say)
var func = (SomeThing item)=> {
return new { ... };
};
I get the error "Cannot assign lambda expression to implicitly-typed local variable". This seems a strange compiler limitation; unless I am missing something, the types are just as non-ambiguous in the 2nd example as they are in the first first: both type parameters are well defined.
Is there any way to do this? Since it's an anonymous type, of course, I don't have any way to use a type to assign it explicitly, so it seems I'd be stuck with making a class for the output type if not.
Update
Shortly after going about my merry way with Jon Skeet's answer, I found a similar dilemma instantiating classes. In case it's not obvious, the same trick can be used to create strongly typed classes using inferred anonymous types.
class Processor<T,U>
{
public Processor(Func<T,U> func) {
}
}
// func is a delegate with anon return type created using method in answer below
var instance = new Processor(func); // does not compile! Requires type arguments!
cannot be created directly, but can be created in much the same way as the trick below:
public static Processor<T,U> Create<T,U>(Func<T,U> func) {
return new Processor<T,U>(func);
}
var instance = Processor.Create(func); // all good
You can do it via type inference:
var func = BuildFunc((SomeThing item) => {
return new { ... };
});
...
static Func<TSource, TResult> BuildFunc<TSource, TResult>(
Func<TSource, TResult> function) {
return function;
}
Note that BuildFunc doesn't really do anything - it just provides the method call needed to get the compiler to do type inference for the generic type arguments for Func<,> - it adds the information that you're interested in Func<,>, basically - that's information which can't be specified as part of a variable declaration, without also specifying the type arguments.

What does this mean in C# or LINQ? - ( () => )

I was going through Jeffrey Palermo's book and came across this syntax.
private void InitializeRepositories()
{
Func<IVisitorRepository> builder = () => new VisitorRepository();
VisitorRepositoryFactory.RepositoryBuilder = builder;
}
What does it mean?
() => indicates a lambda expression that takes no arguments.
In general, it means a function with no arguments.
In this particular example, it creates an anonymous function with no arguments that returns a new VisitorRepository(); object every time.
Func<IVisitorRepository> stands for a delegate which takes no arguments and returns a IVisitorRepository. The creation of that delegate is a lambda function:
() //means no parameters
=> new VisitorRepository()// means it returns a new VisitorRepository
() is the place where you place your variables
Example a common event handled would look like (sender, args)
=> // means throw these parameter into this method
after => you can either drop a one line execution thing like new VisitorRepositor()
OR
you can place a whole function like
Func<IRepository> = (sender, args) =>
{
var myObject = (SomeObject)sender;
return new VisitorReposiroty { id = myObject.SomeId };
}
As other stated it's lambda expression and it really clears your code from method or function that handle a specific event.
Once you read them good it's really damn useful.
The () => syntax is a lambda expression. Lambdas were introduced in C# 3.0 and are used to define an anonymous method for a delegate.
The delegate is defined using the generic Func. So in this case the signature for the delegate is: no input parameters and one output parameter of type IVisitorRepository.
So on the left side of the => lambda array are the names of the input parameters. In case of no input parameters just write (). On the rightside of the => lambda is the code to return the output parameter, in this example: new VisitorRepository().
I suggest read more about lambda expressions in C# to fully understand this code. There is also a generic delegate involved, so you need understanding of Generics and Delegates as well.
Func is a delegate without parmeter and with an IVisitorRepository return value.
() => is a lambda expression creating an anonymous method.
new VisitorRepository() is the content of this anonymous method.
so this line is creating a delegate which is pointing to a anonymous method, which is returning an instance of VisitorRepository.
Func<IVisitorRepository> builder = () => new VisitorRepository()
In the next line, you set the value of a static property to this just created delegate.
VisitorRepositoryFactory.RepositoryBuilder = builder;
After this you can use the property to call the anonymous method, which is creating a new instance of VisitorRepository.
IVisitorRepository repository = VisitorRepositoryFactory.RepositoryBuilder();
In this case, repository will be an instance of VisitorRepository.
It means a function takes no parameters, like:
delegate() {//}

Categories

Resources