Understanding a line of example-code - c#

I'm trying to modify this example to my needs, but one line in particular has me stumped. The line ((Action<List<MessageInfo>>)parm)(msgs); in the chatserver makes absolutely no sense to me. I can see that it typecasts (msgs) to the type ((Action<List<MessageInfo>>)parm);, but it doesn't seem to do anything at all.
I hope that someone can help me understand this, as I have a feeling it one of the last pieces I'm missing of this puzzle...
Kind regards.

They are casting a delegate, then invoking it with msgs.
This bit:
((Action<List<MessageInfo>>)parm);
Casts the delegate. Then it invokes the delegate with msgs.
Breaking it down a bit:
Action<List<MessageInfo>> del = ((Action<List<MessageInfo>>)parm);
del(msgs);
The author just chose to collapse all of that into one line.

The line
((Action<List<MessageInfo>>)parm)(msgs)
is not a simple cast, it's a cast followed by an invocation of the method. Basically it does this:
Action<List<MessageInfo>> action = (Action<List<MessageInfo>>)parm;
action(msgs);

What they are saying is:
Consider that:
parm is an Action
that takes as a parameter a List of <MessageInfo>s
and since Actions are executable, execute it,
passing msgs as a parameter.

Related

Translating C# object method chaining to F#

Rather silly question, but I can't seem to find the correct terminology for it, so all my searching fails.
I have the following C# chain of method calls:
container.Register(Component.For<IMyInterface>().ImplementedBy<MyClass>().Named("MyInstance").LifeStyleSingleton);
How do I write the same in F#?
I can do this:
let f0 = Component.For<IMyInterface> () in
let f1 = f0.ImplementedBy<MyClass> () in
let f2 = f1.Named "MyInstance" in
let f3 = f2.LifestyleSingleton () in
ignore (container.Register f3)
But surely there must be some other, nicer way to structure such a call. No?
Addition
The early answers led me to a solution that worked (I've removed all mentions of ignore since it irrelevant and only confused readers):
container.Register (Component.For<IMyInterface>().ImplementedBy<MyClass>().Named("MyInstance").LifestyleSingleton())
However, one reply states that this should work:
container.Register <| Component.For<IMyInterface>().ImplementedBy<MyClass>().Named("MyInstance").LifestyleSingleton()
but it doesn't. The latter part, the expression after <|, generates a type error
This expression was expected to have type unit but here has type ComponentRegistration<IMyInterface>.
You can do pretty much the same thing in F#:
container.Register <|
Component
.For<IMyInterface>()
.ImplementedBy<MyClass>()
.Named("My Instance")
.LifeStyleSingleton()
Here with some added sugar (<|). You can put the calls on a single line, or like I just did (I prefer that, since it nicely mirrors F# pipelining). One thing to remember is that the arguments need to be parenthesised and with no spaces between function name and the parens (pretty much "C# style").

How do I know if certain extensions methods 'mutate' the object or not?

Feel free to edit 'mutate' from the title if it's a poor choice of wording.
My question is, relatively, simple.
Take the following example:
myCollection.OrderBy(o => o);
How do I know whether OrderBy will/will not order myCollection or whether an assignment (following) is necessary:
myCollection = myCollection.OrderBy(o => o);
Is it a case of having to build it and check every time I encounter an extension I'm unfamiliar with?
Please note: I'm not asking whether this will or will not affect myCollection, I already know the answer to that from using it hundreds of times previous, I'm asking how I'd know.
You can't tell from just the signature.
The best you can do is to investigate the actual code, for example by looking at the .NET Reference Source. Another thing you could do is check the return type. If it is the same as the one it's being called on, it probably doesn't change it, it most likely returns a new instance. Is it a void, then it probably does change something inside.
For your specific case for example, OrderBy: no. See here. It 'just' returns a new OrderedEnumerable.
You can check for the Pure attribute in the class decoration as Steven Liekens said. But in its absence, the only way to know for sure is by:
Experimenting: for example, get an instance of the class and serialize it. Use the method and then serialize it. Compare the results. May not be accurate every time.
Reverse engineering the method: and I hope you have the source code. If you don't, you can use reflection. This will require some judgement if the method is somewhat complex, but this complexity here is subjective.
Reading the docs and trusting them - if the doc is present. This is the sensible thing to do with the .NET Framework types, and an exercize of faith otherwise.
One way is to find out if the method or its class is marked as [Pure]. Pure code does not modify input values.

How to execute function on Parallel.ForEach?

I'm trying to:
Parallel.ForEach(listOfNames, name => DoSometingWithName(name));
while VS asks me to convert method to group, while i can't since this method is used from other places as well. So i don't want to copy paste the code around.
Is there a way to ?
Caused by ReSharper thus guys without it never seen this message. I thought it was compiler error.
Elegant work around would be:
Parallel.ForEach(listOfNames, DoSometingWithName);
Not sure it is more readable though.
Not sure what you mean, but did you search this syntax?
Parallel.ForEach(listOfNames, name =>
{
//Place your code here.
DoSometingWithName(name);
});

Does a method name starting with "Does" look good?

Is it a good practice to start a method name with "Does" (in C#)? It looks a little bit weird to me, so I would like to get your opinion.
I am writing a method which check if an account exists or not, should the signature be
"bool DoesAccountExist(id)"? Is there a better name?
Thanks!
Personally I'd go with AccountExists(id) in this case, since it will look more natural in an if block
if (AccountExists(id)) { }
We always use Is for any method that will return a boolean, so in this case we would call the method
IsExistingAccount(id)
I usually leave off the Does and simply use AccountExists(id).
To me it looks more natural later in code such as:
if(AccountExists(id))
{
ValidateLogin();
}
The alternative would be something like:
if(!DoesAccountExist(id)) {}
seems odd to me. I would read that as if does account not exist? Which makes less then account does not exist.
The "Is" prefix idiom help clarify methods like Array "Empty" which might mean "empty the array" or "is the array empty?". If used consistently "IsEmpty" is clearly the bool return and by convention "Empty" becomes clear as the action of emptying.
In the context of the question I agree with #Andy Whites second suggest:
if (IsExitingAccount) ...
Here the 'Is' triggers a strong automatic implication of bool return constistant with its use else where (IsEmpty, IsNull, etc)
I think AccountExists is your best bet, but one other option is: IsExistingAccount. For methods or properties that return a boolean, it can be useful to use a naming convention where the method begins with the word "is". If you use "is," you'll have to rephrase the rest of the method name so that it makes sense to the reader.
Can or Is could be used like CanCopy or IsAccountExists is fine too. Following predefined conventions make code more readable. To be frank Does prefix looks a bit wierd to me as well.
Another Option is to use the standard C# plural of Is, Any.
AnyAccountsExist(id)

Need concise definition of "delegate"

I need a short description of how "delegation" works in programming, preferably in one sentence. Even better to use analogies
A type-safe function-pointer.
A type safe function pointer.
Even better to use analogies
Delegates are like violence. If they haven't solved your problem yet then you haven't used enough.
OK, this joke is not original, so sue me.
Seriously now. Delegates are like... delegates. Hence the name. What is a delegate in real life? A delegate is someone who acts on behalf of another. You delegate work to them and they perform that work. You want to trade fifty shares of XYZ corp, you don't go down to the trading floor and do it yourself, you delegate that work to your broker who does it for you; how they do it, you don't care so long as it gets done. The broker is your delegate; they do the work on your behalf.
A delegate is an object that represents the ability to do work on demand. You create a delegate that does a particular job, and when you want the job done, you ask your delegate to go do it for you.
A delegate wraps a method into a type safe object reference the way a beer opener wraps a method (opening beer) in a handy tool (the beer opener) that can be used again and again for different kind of beer bottles.
There's input defined for the beer opener, a certain type of bottle and a force (your hands). It holds the key to an action of which the form is always the same. Likewise, there's input defined for the delegate, which holds the key, a contract, to an action (showing a form) with certain input (the form).
Note: this is not about 99 bottles of beer ;)
Note (2): you can open a beer without a beer opener, the same way you can use a method (even its reference) without a delegate. It's just messier and less clear, but it can be a lot more fun though.
The best analogy I can think of comes from the C terminology, which is "pointer to function".
The idea is that you need to be able to invoke a piece of code, but that piece of code you're going to invoke isn't known until runtime. So you use a "delegate" for that purpose.
A delegate is a type that references a method.
A delegate is like an intern, as in when you say "Hey, I need an intern to bring me a cup of coffee."
With luck you will get someone who is capable of executing "bring me a cup of coffee". Different interns might execute that task differently, one may run out to Starbucks, for example. Another might run around until she finds a non-empty coffee pot somewhere in the building and pour you a cup.

Categories

Resources