C# lambda variable initialization [duplicate] - c#

This question already has answers here:
What does the => operator mean in a property or method?
(7 answers)
Closed 7 years ago.
Today for the first time I seen something similar to this:
private string m => string.Empty;
using lambda to initialize a variable. Why doing it like this and what are the benefits?

It's called Expression-Bodied Properties and it's merely a shortcut for getter-only properties:
private string m
{
get { return string.Empty; }
}
As for the benefits of this approach, I guess you can treat it as syntactic sugar that is only saving you some keystrokes.
See Roslyn Wiki

It's not a variable, it's an expression bodied property. A read-only property, in your case returning string.Empty.
It's the same as
private string m { get { return string.Empty; } }
It's one of the new features introduced in C# 6.0. The benefit is shorter, more concise code. Especially if you have a class with a lot of simple read-only properties.
If you want to see a real-world example of this syntax, check the this post on Eric Lippert's blog. As you can see, there's a lot of one-line methods and properties there. Without expression-bodied properties and members, the code would be much longer. And a considerable part of it would be curly braces.

This is not actually a variable initialization, this binds the lambda expression "string.Empty" to "m", so whenever you dereference "m", it will actually evaluate your lambda expression.
For further reading check out this github page (section "Expression-bodied function member")

Related

How to create assignable class/struct/data type in c#? [duplicate]

This question already has answers here:
Overloading assignment operator in C#
(3 answers)
Closed 2 years ago.
I have a complex object type for which I'm overriding the "base.ToString()" method so that it returns a string property value.
for example:
class foo
{
public string StringValue{get;set;}
public int SomeOtherValue{ get;set;}
public override ToString()
{
return StringValue;
}
}
So this allows me to use retrieve the value of the StringValue property easily.
Is there a way in which I can override or extend the base functionality so that I can use simple code such as below to set the StringValue property?
foo aFoo = new foo();
aFoo = "Some string value";
You can use implicit cast operator overload: http://msdn.microsoft.com/library/z5z9kes2.aspx
You can't overload the = operator as stated here
See this page for a complete list of overridable operators.
No, this is not possible. The assignment operator is not overridable and for good reason.
Developers are, even within the confines of C# and modern object-oriented programming languages, often "abusing" the system to make it do things it's not supposed to do. If you could assign a different meaning than passing a reference value to a variable to an assignment operator, think of the chaos that would create when inexperienced developers use it.
What you can do is to provide methods that allow your object to take its values from a string, like so:
afoo.TakeValuesFrom("Some string value");
or
MyThingy afoo = MyThingy.FromString("Some string value");
which would be almost identical to what you are asking, and perfectly legal and readable.
No you cannot. It is a protected part of the C# language specification. Being able to override this would be like overriding your bodies ability to breathe air with breathing water.
Use implicit conversion operators. It will do exactly what you need

What is this type of property syntax called: int x=> _x; [duplicate]

This question already has answers here:
Lambda for getter and setter of property
(3 answers)
Closed 5 years ago.
I seemed to have missed the memo on this particular syntax, as I ran across it today and have not seen it before:
private readonly PageContext _pageContext;
internal PageContext PageContext => _pageContext;
I can guess that it means to return the private value, but what is this type of syntax called, and why would one use it instead of a getter like this?
internal PageContext PageContext{get{return _pageContext}};
This is called expressions bodies syntax, and it has been introduced in C# 6. You can find more info here. As it is stated there:
Properties and indexers can have getters and setters. Expression
bodies can be used to write getter-only properties and indexers where
the body of the getter is given by the expression body:
Regarding your second question:
and why would one use it instead of a getter like this?
I would use it, in order my code to be more compact. I find it more succint than having to use the curly braces, the return statement, etc.
By the way if you want to declare just a readonly property you could make use also the following syntax, avoiding to declare the backing field, _pageContext:
internal PageContext PageContext { get; }
Update
In the example that has been presented by the OP, if we make use of this
internal PageContext PageContext { get { return _pageContext } };
or the following:
internal PageContext PageContext => _pageContext;
we would always get the same result. The latter is a syntactic sugar of the first one and it should be preferred since make the code more compact and clear.
In both of these cases _pageContext would be initialized in the constructor of the corresponding class, since this is a readonly field and it's value is not declared at the definition of the field:
private readonly PageContext _pageContext;
On the other hand the following expressions are not the same:
DateTime TimeWhenCalled => DateTime.Now;
DateTime TimeWhenInitialized { get; } = DateTime.Now;
The first one would return each time that would be called the value of the DateTime.Now for this moment. Whereas the second would return always the same value, the value of DateTime.Now, when an object of the class that contains this property, is created and the runtime hit this line.
It is called an Expression Bodied Member. You can use it instead of a getter to save typing and write "cleaner" code.
It is an Expression Bodied Property.
This syntax is not limited to properties alone, you can find further information here
It is nothing more than some syntactic sugar.
This is called expressions bodies syntax, and it has been introduce in C# 6.0.
If you want provide getter only then you can use it.
It is similar like this
public string Abc{ get{return "this is string";};}

C# method meaning [duplicate]

This question already has answers here:
What does the '=>' syntax in C# mean?
(7 answers)
Closed 8 years ago.
so I am looking at this C# method
if (IsInDesignMode)
{
// Only runs in design mode
_dataService.GetMachine(_machines[0].Machine.SerialNumber, (machine, error) => //<-- this is what I am confused about
{
SelectedMachine = new MachineViewModel(machine);
});
}
I understand the if() statement and the SelectedMachine = new MachineViewModel(machine); line.
But I am confused about the commented line.
_dataService calls a GetMachine method passing in _machines[0].Machine.SerialNumber param and (machine, error) => {}. It is not an "equal or less than" statement right?.
It kinda looks like a Javascript code to me...?
Does the method say,
If IsInDesignMode {
dataservice.GetMachine(machine serial number, machine error is new MachineViewModel)
}
Can any one explain what => { } this is? thank you very much!
The part you are asking about is an anonymous method that uses a lambda expression. It is commonly used in callbacks.
When you write this
(machine, error) => { SelectedMachine = new MachineViewModel(machine); }
you are making a function that has no name (and therefore cannot be reused by name, like a regular method). It is very convenient in situations when you need to produce a piece of callable code that needs to be used only once, e.g. in callbacks.
Note that the method does not have to be anonymous: you could make an equivalent named method. However, an since the anonymous method is built in the context of the method where it is used, the variables from the context are available to it. Your anonymous method assigns SelectedMachine, which is probably a property of your class. In the same way, anonymous methods can access local variables as well, which is a very powerful mechanism of combining together a state and a piece of code that operates on it.
To be more precise. It is an Anonymous method using lambda expression.
the sign you are asking '=> { }' is called lambda expression.
Usually it is used with Delegate type like func, Action, predicate and others.
Have a look on the above types to make yourself more clear.
It is a lambda expression. Have a look on this page for more info: http://msdn.microsoft.com/en-us/library/bb397687.aspx

Is it possible to override assignment "=" in C# [duplicate]

This question already has answers here:
Overloading assignment operator in C#
(3 answers)
Closed 2 years ago.
I have a complex object type for which I'm overriding the "base.ToString()" method so that it returns a string property value.
for example:
class foo
{
public string StringValue{get;set;}
public int SomeOtherValue{ get;set;}
public override ToString()
{
return StringValue;
}
}
So this allows me to use retrieve the value of the StringValue property easily.
Is there a way in which I can override or extend the base functionality so that I can use simple code such as below to set the StringValue property?
foo aFoo = new foo();
aFoo = "Some string value";
You can use implicit cast operator overload: http://msdn.microsoft.com/library/z5z9kes2.aspx
You can't overload the = operator as stated here
See this page for a complete list of overridable operators.
No, this is not possible. The assignment operator is not overridable and for good reason.
Developers are, even within the confines of C# and modern object-oriented programming languages, often "abusing" the system to make it do things it's not supposed to do. If you could assign a different meaning than passing a reference value to a variable to an assignment operator, think of the chaos that would create when inexperienced developers use it.
What you can do is to provide methods that allow your object to take its values from a string, like so:
afoo.TakeValuesFrom("Some string value");
or
MyThingy afoo = MyThingy.FromString("Some string value");
which would be almost identical to what you are asking, and perfectly legal and readable.
No you cannot. It is a protected part of the C# language specification. Being able to override this would be like overriding your bodies ability to breathe air with breathing water.
Use implicit conversion operators. It will do exactly what you need

What is '=>'? (C# Grammar Question) [duplicate]

This question already has answers here:
What does the '=>' syntax in C# mean?
(7 answers)
Closed 8 years ago.
I was watching a Silverlight tutorial video, and I came across an unfamiliar expression
in the example code.
what is => ?
what is its name? could you please provide me a link?
I couldn't search for it because they are special characters.
code:
var ctx = new EventManagerDomainContext();
ctx.Events.Add(newEvent);
ctx.SubmitChanges((op) =>
{
if (!op.HasError)
{
NavigateToEditEvent(newEvent.EventID);
}
}, null);
It's a lambda expression.
If you're familiar with anonymous methods from C# 2, lambda expressions are mostly similar but more concise. So the code you've got could be written like this with an anonymous method:
var ctx = new EventManagerDomainContext();
ctx.Events.Add(newEvent);
ctx.SubmitChanges(delegate(Operation op)
{
if (!op.HasError)
{
NavigateToEditEvent(newEvent.EventID);
}
}, null);
Aspects of anonymous methods such as the behaviour of captured variables work the same way for lambda expressions. Lambda expressions and anonymous methods are collectively called anonymous functions.
There are a few differences, however:
Lambda expressions can be converted into expression trees as well as delegates.
Lambda expressions have a number of shortcuts to make them more concise:
If the compiler can infer the parameter types, you don't need to specify them
If the body is a single statement, you don't need to put it in braces and you can omit the "return" part of a return statement
If you have a single parameter with an inferred type, you can miss out the brackets
Putting these together, you get things like:
IEnumerable<string> names = people.Select(person => person.Name);
Lambda expressions don't support the "I don't care how many parameters there are" form of anonymous methods, e.g.
EventHandler x = delegate { Console.WriteLine("I was called"); };
Lambda operator:
A lambda expression is an anonymous function that you can use to create delegates or expression tree types. By using lambda expressions, you can write local functions that can be passed as arguments or returned as the value of function calls...
Huzzah!
I couldn't search for it because they are special characters.
Sometimes the old-fashioned ways are the best. This worked for me:
Start Visual Studio 2008 or later
Hit F1
Once the Help Document Explorer has come up, ensure the Index tab is selected in the left hand pane
Enter => in the Look for field
The first item in the list is now the help article you need.

Categories

Resources