Lambda function in C# context and OOP [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I am a beginner in c# and really interested in learning the language by going deeper. Recently used Lambda function to make a piece of my code but no idea how it worked.
I was mapping values from a list by writing hard code. See below:
var validRatings = new List<int> { 1, 2, 3, 4, 5 };
Used Lambda and it worked:
var validRatings = settings.grossAlphas.Select(ga => ga.fundRating).ToList();
I understand Lambda functions are anonymous but how are they different than regular functions and how do they fit in OOP context within C#?

Lambda functions are anonymous but how are they different than regular functions?
"How are X and Y different?" is in general not a good question for StackOverflow. Here, here's an apple tree and an oak tree; how are they different? Hard to say.
Briefly though:
Lambdas can be converted to delegates or expression trees. Regular functions can only be converted to delegates.
Lambdas can be expression bodied or statement bodied. Before C# 6, regular functions could only be statement bodied.
Lambdas can have their formal parameter types inferred from context; regular functions cannot.
how do they fit in OOP context within C#?
They don't. Lambdas are an idea from functional programming, not from object oriented programming. The fundamental idea of OOP is that functionality is logically connected to data; lambdas are the exact opposite of that. Lambdas are about the decoupling of functions from data objects.
If that doesn't answer your question, then ask a more clear question. What do you mean by "the oop context"?

A normal method can be called by name anytime in the code, but there are cases when we need some block of code that would be executed just once or the caller is only one, so if you see in the above code.
The main purpose of lambda expressions is to give calling code flexibility to pass it's own implementation, for example in the above case, you can have specified your own implementation and project my original collection to a new collection which contains one property named fundRating, chances are you only need this block of code for this use case, so lambda expression creates anonymous method which can only be called by the Select() method implementation.
Hope it helps!

You could create a function and name it, like so:
private string getFundRating(GrossAlpha ga)
{
return ga.fundRating;
}
And then you could pass that function in your Select. like so:
var validRatings = settings.grossAlphas.Select(getFundRating).ToList();
This would be an example of not using a lambda. In that case you are using a named function. You could use the same function somewhere else in your code or in another linq statement.
In the example you provided, you create a function on the fly, don't even name it and pass it in the Select.
Note: I assumed you had an object named GrossAlpha, and that settings.grossAlphas returns a list of those.
Regarding the other part of your question. How do they fit in the context of OOP, I can't explain it much better than Eric Lippert did.

A simple way to think of an anonymous method, albeit not a pure definition, is a method that you want to use once and move on. They're called anonymous because the aren't named methods. Lambdas, in C#, are an extremely powerful way of linking commonly used methods based on your individual objects.
What your code is doing, in one line would take many lines to write out unique methods based on every one of your classes.
To break down what your code is doing dot-by-dot:
var validRatings = settings.grossAlphas.Select(ga => ga.fundRating).ToList();
grossAlphas.Select(...): is walking through your enumeration (List, Array, etc...) object by object and aggregating them according to the parameters you supply inside the .Select(...).
ga => ga.fundRating: you are saying that you want to aggrigate ONLY the fundRating attribute from each object.
.ToList(): is making your enumeration into a List<int>().
This saves you from writing a List<int> GetFundRatings() for a single time you need to use a list of FundRatings.
Also see:
What is a lambda (function)?
C# Lambda expressions: Why should I use them?

Related

var and dynamic Keyword in C# , related to Polymorphism? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
Can we say var keyword is Compile time Polymorphism and Dynamic is Run Time Polymorphism?
var a=10; (Compile time Polymorphism)
dynamic a=10; (Dynamic is Run Time Polymorphism)
a="XYZ"; (Dynamic is Run Time Polymorphism)
I don't think you can link var and dynamic with polymorphism exactly. Polymorphism is about actions and behaviours and not data type or bindings.
var is evaluated at compile-time and dynamic is evaluated at runtime. You are correct there though.
for a better understanding look into What's the difference between dynamic (C# 4) and var?
Also, a suggestion. A little bit of reading and searching would have answered your query.
More Description
Polymorphism is about an entity that can take many forms or behave differently. As an object can be a parent class instance or a child class instance. Now var cannot take multiple types on its own. Its type is just inferred with the type of object being assigned to it. So technically var is not compile-time polymorphism. Rather it depends on the object being assigned to that.
So, var and dynamic might help you achieve or demonstrate polymorphism, but they do not themselves are examples of polymorphism.
var and dynamic have no relation whatsoever to polymorphism. Polymorphism means that you can provide an instance of a more-derived type when a less-derived type is required. var and dynamic are just syntactic sugar; the compiler does the work of figuring out what type you mean or need given the situation (in the case of dynamic). Apples and oranges.

Why does the "out" parameter exist in C# as a language construct? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
Question
Why does the "out" parameter exist in C# as a language construct?
Elaboration on the question
Why does it exist in the first place? Aren't there better language features to get the same effect one can get with the "out" parameter?
Isn't it strange to make an value type behave like a reference type?
Aren't there better ways to return multiple values from a method?
Is it a historical thing, meaning with the first versions of C# there was no way to achieve the things one can achieve with the out parameter but now there are newer features and it's just kept in the language for backwards compatibility?
What I'm not asking
I'm not asking what it does
out parameter modifier (C# Reference)
I'm not asking how it is used
https://stackoverflow.com/a/8128838/33311
What is the purpose of the "out" keyword at the caller (in C#)?
I'm not asking what the difference between "ref" and "out" is
What's the difference between the 'ref' and 'out' keywords?
I read that one should avoid its use and choose other constructs
Best practice of using the "out" keyword in C#
I haven't found any duplicates while reading the similar questions.
Expected answer format
I'd love to hear something like, "Look, here is a problem you can only solve with the use of the "out" parameter language construct and here is a code example for it...".
Or, "Look, this used to be the only way to solve the following problem ...code example..., but since C# version ... the better way to solve is like this ... code example...".
No opinions please.
The C# compiler performs definite assignment checking. That requires it to know exactly when a variable is assigned. Usually not hard to figure out, an assignment is pretty easy to see back.
But there is a corner-case is when a variable is passed by reference to another method. Does the method require that variable to be assigned before the call, then modifies it, or is it only ever going to assign it? The compiler in general cannot know, the method may live in another assembly with the method body unavailable. True for any .NET Framework assembly for example.
So you have to be explicit about it, you use ref when the method requires the parameter to be assigned before the call, out when the method only ever assigns it. Great feature btw, it eliminates an entire swath of very common bugs.
One note about other incorrect answers on this question. Data flow plays an important role in pinvoke as well, the pinvoke marshaller needs to know whether the convert any data returned by an unmanaged function. It does not pay attention to out vs ref keywords, only to the [In] and [Out] attributes. More about that gritty detail in this Q+A.
One reason would be for compatibility with e.g. Win32 APIs. Some method declarations for Win32 API calls will require the use of out and/or ref if you want to call them directly from C#.
You can find some examples of such method declarations at pinvoke.net:
http://pinvoke.net/search.aspx?search=out&namespace=[All]
Why does it exist in the first place? Aren't there better language features to get the same effect one can get with the "out" parameter?
Whats "better"? Arguing based on C#7 where things are a bit easier, is this:
public static (bool Succesful, int Value) TryParse(string s) { ... }
var parseResult = TryParse(s);
if (parResult.Succesful)
DoSomething(parResult.Result);
better than?
if (int.TryParse(s, out var i))
DoSomething(i);
Hmmm....
And before native tuple suport, you'd actually have to implement a struct/class to be able to return multiple values.... yuck. True that the out solution wouldn't be as clean either, but still a better option than having to litter your code base with tons of lightweight container classes to simply have methods return multiple values.
Isn't it strange to make an value type behave like a reference type?
Why? Even if its only for backwards compatibility or for interop, its a needed language feature.
Aslo, your mixing up things here. If you want pass by reference semantics, you'd use the ref keyword. The out keyword means that the parameter is meant to be used as a return value; the fact that it needs to be passed by reference is an implementation detail.
Aren't there better ways to return multiple values from a method?
This is basically your first question rewritten.
Is it a historical thing, meaning with the first versions of C# there was no way to achieve the things one can achieve with the out parameter but now there are newer features and it's just kept in the language for backwards compatibility?
Backward compatibility is the obvious and important reason. Also, just because there are better ways to do things doesn't necessarily mean that language features should be removed. You could then make a case for many other language constructs: for loops, goto, etc.

The best way to pass values between classes in C# [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
First case:
If I have a set/get method for a value inside the class A, I can
set that value from the class B and use it inside A.
Second case:
I can just pass the value in a traditional way like Method(value);
Please, explain me which way is better.
I appreciate your answers.
Properties (what you call the set/get method) are essentially a "syntax sugar" on top of regular C# methods. There will be no performance difference between using properties and using regular methods.
Generally, though, you should prefer properties to methods for readability, i.e. when they present an appropriate semantics to the readers of your class.
Setters and Getters should be used for general properties of classes, used across several methods.
A parameter to a method call is appropriate for a variable tied to that one method (though possibly stored and used elsewhere, for instance if it is part of initialisation).
As always, do what looks best and works well in your context. If the using code feels awkward, look for another way. If it feels right, it's probably OK.
The goal of Object oriented programming is to have your data and operations together.
The goal is to reduce coupling between different kinds of objects so that we can re use the classes.
Never expose the data inside the class to the outside world but provide interfaces to do so

Why anonymous types aren't dynamic as the ExpandoObject? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
With dynamic we pretty much have a dynamic pointer, but not exactly a dynamic object. The true dynamic object in C# is the ExpandoObject, but that is a really unknown class for most of people. The expando allows creating and removing members at runtime, much like a hash (similar to JavaScript).
Why the ExpandoObject goodness was implemented in a separate class rather than just being, let's say, implemented as a feature of anonymous types?
Maybe that wouldn't be a good move because the lacking of type-safety? Or maybe due the (DLR) overhead involved?
Because anonymous types have other very important feature - they provide you compile time type safety.
And because dynamic and anonymous types are just different concepts. The first one gives you ability to dispatch object members at runtime, the second lets you create statically typed objects with some base functionality (equality, hashcode, etc) without creating corresponding POCO classes. Why should they be implemented in the same way then?
btw. I use them quite a lot and really rarely needed to use dynamic to deal with them. Are you sure you're using these language features correctly?
Update
I think that's very important part of anonymous types tutorial:
If you must store query results or pass them outside the method boundary, consider using an ordinary named struct or class instead of an anonymous type.

Is using var in c# really that bad? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
So I'm creating a connection library for a colleague of mine to save him time on his current project. My colleague will use this library in his c# application to connect to a rest api. Within the library I created Handlers for each request(GET / POST / PUT / DEL). When his application talks to my library i will return the response like this:
return client.PostAsync(url, content).Result;
This returns a dynamic object from the rest api.
Today he used my library and couldn't get it to work in combination with his application for some reason. I told him to use a var and that it would work like this:
var x = API.CreateTraject(parameter1,parameter2);
He refused to use var and ended up spending about 40 min figuring out how to get it to work without it. Then he blamed me for returning a dynamic object and that he will never use var because explicit is better so he told me.
Im normaly working as mobile developer (IOS / Android) where i use var all the time.
Now my question is:
Is it really so bad to use var? Should I convert the response in my library so he can explicitly type it in his application? In my opinion I would rather use var and save some time then spend 40 min trying go make it explicit.
Is it really so bad to use var? Should I convert the response in my library so he can explicitly type it in his application? In my opinion I would rather use var and save some time then spend 40 min trying go make it explicit.
var, in C#, is merely a compiler "trick". There is no dynamic typing involved, and the compiled code is exactly the same. When you hover your mouse over the variable, the IDE will tell you the "real" type that gets used.
Whether he uses var or your actual return type shouldn't matter at all in terms of how you create your library.
If your library is returning dynamic unnecessarily, that may be a different issue, and one which the user may have valid complaints. Unlike var (which is merely a compile time trick), dynamic does change the behavior significantly.
Alternatively, if you're returning anonymous types from your library, you may want to consider making an actual class for your values. Anonymous types are really only intended to be used within a local scope, and shouldn't be part of any public API.
There is nothing illegal with using var, it just lets the compiler figure out what data type the object should be.
The only danger is that you, the programmer, don't know what it is until you mouse over. This can lead to problems where you thought it was one thing, but it turned out to be something else.
It is okay to use var, it's not illegal or anything.
But I think if you know the type of variable, declare the variable with the type. This will make your code easier to read.
It's not bad to use implicit typing, it's just a matter of style. I personally use it a lot simply because it makes all my variable declarations take up the same amount of space, regardless of type.
However, using dynamic definitely can be bad, especially when it's used excessively. It means that type safety checks that can be performed compile-time need to be deferred until run time. Occasionally that's useful, but it can have performance impacts. Unless you really need to return a dynamic, I'd strongly recommend returning a specific type from your API method.
For what it's worth, if your coworker is so opposed to implicit typing he could've just used this:
dynamic x = API.CreateTraject(parameter1,parameter2);
var has nothing to do with dynamic. var is about type inference.
Your methods should not return dynamic to begin with. In any case create Generic Methods and let the consumer (your Colleague) decide what type of object the method will return.

Categories