Automatic Properties (LINQ) - c#

Would someone be able to explain or provide a link to a page that describes what Automatic Properties are (in relation to LINQ) in lamens terms please

Automatic properties - better call them "auto-implemented properties", are a new syntax sugar added in latest C# versions as some comment pointed out.
It consist in a property that declare its accessors without body and C# compiler creates the corresponding private fields for you:
public string Name
{
get;
set;
}
Note that this isn't an abstract member, becase it'd be marked with the appropiate attribute "abstract"!
Additionally to that, these accessors, as non-auto-implemented ones, can have visibility attributes: private, internal, public (default behavior):
public string Name
{
private get;
internal set;
}

Here is an automatic property in C# 3.0:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
compared to a non automatic property:
public class Person
{
string _FirstName;
string _LastName;
public string FirstName
{
get { return _FirstName; }
set { _FirstName = value; }
}
public string LastName
{
get { return _LastName; }
set { _LastName = value; }
}
}
Here's the post by Dan Wahlin on automatic properties, from where I got the above code.

Refer to the following:
Auto-Implemented Properties
Using Automatic Properties in LINQ

Related

Should I use private fields in my C# class or public Properties are good enough?

as my question said I'm confused in case where should I use private fields or not..
Here is my Person class for example:
I know it's useful to use private fields when I want to get FullName quickly..
Actually that's only example where I'm adding addition code in some of my getters,
so I would like to avoid private fields, so I might start using public properties because anyway in the background private field will be created?
private string _firstName;
private string _lastName;
public string FullName
{
get { return _firstName + _lastName; }
}
Anyway, could I do something like this, remove private fields - > add only public properties ? I guess there is no issue about this code below.. ?
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullName
{
get { return FirstName + LastName; }
}
Should I prefer example 2? I mean is there any problems if I stay with example 2? Because I want my classes to look cleaner without private fields :)
The answer here will really depend on whether you want the first/last name to be on the public API. If you do: 2 is ideal for your typing convenience. At runtime, thanks to JIT magic, 1 and 2 will be largely indistinguishable (except for the accessibility concern), so you might as well go with the most convenient and expressive form, which is usually: 2.
Even 1 could use private automatically implemented properties if you so wish, although it is pretty rare to see that in reality - most code either uses public properties or private fields, depending on the intent; public fields are anecdotally rare, as are private properties.
It might also make sense to have the first and last names public but read-only, i.e.
public string FirstName { get; }
public string LastName { get; }
public string FullName => FirstName + LastName;
or public but only writable inside the type:
public string FirstName { get; private set; }
public string LastName { get; private set; }
public string FullName => FirstName + LastName;

Why create public wrappers to private members in a class?

I've always had this question, but I've blindly followed on so far.
This is from a piece of example code:
Why do this:
public class EmployeeInfo
{
int _EmpNo;
public virtual int EmpNo
{
get { return _EmpNo; }
set { _EmpNo = value; }
}
string _EmpName;
public virtual string EmpName
{
get { return _EmpName; }
set { _EmpName = value; }
}
}
when there's nothing additional, such as calculations or validations, being done during getting/setting?
Will this suffice?
public class EmployeeInfo
{
public int EmpNo { get; set; }
public string EmpName { get; set; }
}
Also, why virtual for the public member wrappers?
Why do this?
There's really no reason to since the addition of auto-implemented properties in C# 3.0. It could be legacy code that hasn't been changed, old habits, or keeping consistency with pre-C# 3 code.
Will this suffice?
No - you've converted the virtual properties to non-virtual. So they are not completely equivalent.
The equivalent would be
public class EmployeeInfo
{
public virtual int EmpNo { get; set; }
public virtual string EmpName { get; set; }
}
Also, why virtual for the public member wrappers?
So that a derived class can override the logic for the properties - to add validation, change notification, etc.
When does the shortened form actually have an impact?
When the backing fields are referenced by the internal code of the class (which can be detected at compile-time), or when they're accessed by reflection (which cannot be detected until run-time, or via static code analysis).
An "auto-implemented" property actually gets a backing field created by the compiler, so in that sense they're equivalent if the only place the backing field is referenced is within the property code.
You have two questions. First is changing properties to auto implemented properties, they should be equal, but you removed virtual keyword, that makes them different.
So, what is virtual. That keyword will allow derived classes to override the get/set for the said property.
See: virtual C#
The virtual keyword is used to modify a method, property, indexer, or
event declaration and allow for it to be overridden in a derived
class.
Your class with auto-implemented properties would be equal if you have:
public class EmployeeInfo
{
public virtual int EmpNo { get; set; }
public virtual string EmpName { get; set; }
}
Later you can override a property and leave the other to maintain the parent behaviour, like:
public class ManagerInfo : EmployeeInfo
{
private int _EmpNo;
public override int EmpNo
{
get { return _EmpNo; }
set
{
if (value < 100) throw new Exception("EmpNo for manager must be greater than 100");
_EmpNo = value;
}
}
}
Depends if you want to see the field publicly or not,
if your only going to use the field inside the declaring class then you don't need to wrap it in a property, its only if you need to expose it publicly or down the inheritance tree that you should have the property
public string EmpName { get; set; }
is just a compiler short cut to
private string _EmpName;
public string EmpName {
get{ return _EmpName;}
set(_EmpName = value; }
}
they are functionally identical.
However there are things that the short cut wont let you do, for example you want to raise an event when the property changes.
there there is also your use of Virtual which is an inheritance modifier
Virtual instructs the code that it needs to look DOWN the inheritance tree for a newer implementation.
so in
class A
{
public string Data
{
get{return "A";}
}
public virtual string VData
{
get{return "A";}
}
}
class B:A
{
public new string Data
{
get{return "B";}
}
public override string VData
{
get{return "B";}
}
}
then if you do
A obj = new B();
obj.Data; //return A
obj.VData; //return B
It looks like the code in this form:
$type _$var;
public virtual $type $var
{
get { return _$var; }
set { _$var = value; }
}
Was generated using a tool, template or snippet. As habits hardly ever change and tools, templates and snippets hardly ever get updated, I guess they were created before auto-implemented properties (public $type $var { get; set; }) were introduced to the C# language.
For the code you show, it's perfectly valid to have the equivalent:
public virtual $type $var { get; set; }
As you can override the auto-implemented property and add a backing field, validation and whatever when required.
The expanded form is the traditional way to do it:
public class MyClass
{
int _myInt;
virtual public int MyProperty
{
get
{
return _myInt;
}
set
{
_myInt = value;
}
}
}
However, the shorter form is called "auto properties", introduced in C# 3.0.
public class MyClass
{
virtual public int MyProperty { get; set; }
}
These code blocks are equivalent. This is a good practice for keeping your code concise.
One thing to consider: You aren't able to make the internal variable protected with auto properties, so if you create a derived class and override your property, you'll need to use base.MyProperty to access it, or use the expanded form.

What does {get; set;} means ? [duplicate]

This question already has answers here:
What is the { get; set; } syntax in C#?
(20 answers)
Closed 9 years ago.
Consider the following code :
public class Order
{
public int OrderID { get; set; }
public DateTime OrderDate { get; set; }
public decimal Total { get; set; }
}
I don't understand what does the { get; set; } means .
I usually use get and set like this :
class Person
{
private string name; // the name field
public string Name // the Name property
{
get
{
return name;
}
set
{
name = value;
}
}
}
So, what does the { get; set; } means ?
Thanx
Using { get; set; } by itself translates exactly to what you usually use.. its just shorthand for it.
The compiler creates an automatic backing field.
So this:
public string FirstName { get; set; }
..is compiled to this:
private string _firstName;
public string FirstName {
get {
return _firstName;
}
set {
_firstName = value;
}
}
This all happens at compile time, therefore you cannot directly access the backing field (because it isn't actually available until the code is compiled).
After the compiler converts the above.. automatic properties are actually turned into methods.
So the above is turned into this:
public void set_FirstName(string value) {
_firstName = value;
}
public string get_FirstName() {
return _firstName;
}
Then some IL is produced to notify tools like Visual Studio that they are properties and not methods.. somewhat like this:
.property instance string FirstName() {
.get instance string YourClass::get_FirstName()
.set instance void YourClass::set_FirstName(System.String)
}
These are auto implemented properties.
Compiler will extend it with a backing field for you. However, you can't access that field directly.
In C# 3.0 and later, auto-implemented properties make property-declaration more concise when no additional logic is required in the property accessors. They also enable client code to create objects. When you declare a property as shown in the following example, the compiler creates a private, anonymous backing field that can only be accessed through the property's get and set accessors.
Read more on MSDN: Auto-Implemented Properties (C# Programming Guide)

Setting only a setter property

I have an object model that has a property like this:
public class SomeModel
{
public string SomeString { get; set; }
public void DoSomeWork()
{
....
}
}
I want the DoSomeWork function to execute automatically after the SomeString property changes. I tried this but it's not working:
public string SomeString { get; set { DoSomeWork(); } }
What's the correct syntax?
Use a private field instead, like this ...
public class SomeModel
{
private string someString = "";
public string SomeString {
get { return this.someString; }
set {
this.someString = value;
this.DoSomeWork();
}
}
public void DoSomeWork()
{
....
}
}
You can't do this with automatic properties - you'll have to create a "manual" property backed by a field.
private string _someString;
public string SomeString
{
get { return _someString; }
set
{
_someString = value;
DoSomeWork();
}
}
If you really can't deal with this boilerplate (say you'd have to do this hundreds of times), consider using an AOP framework like PostSharp to implement this on your behalf - you'd just need to declare an automatic property and an attribute to get the binary rewriter to implement the desired scheme.
This will work...
private string _someString;
public string SomeString { get { return _someString; } set { _someString = value; DoSomeWork(); } }
private string _someString;
public string SomeString
{
get
{
return _someString;
}
set
{
DoSomeWork();
_someString = value;
}
}
C# team has introduced the auto-implement properties in C# 3.0. with the logic of minimizing the model making which is backed by an anonymous field created by compiler. this one is used when you don't need to implement any additional logic on a property of an object class. so it just followed as.
public string Name{ get; set;}// auto-implemented property. no additional logic.
if we want to add some logic as you want to add one function. we must be writing a manual property backed by a private field as like below.
private string _Name;
public string Name
{
get {return _Name;}
set {
_Name=value;
DoSomething(); //Additional logic implemented.
}
}

c#: getter/setter

I saw something like the following somewhere, and was wondering what it meant. I know they are getters and setters, but want to know why the string Type is defined like this. Thanks for helping me.
public string Type { get; set; }
Those are Auto-Implemented Properties (Auto Properties for short).
The compiler will auto-generate the equivalent of the following simple implementation:
private string _type;
public string Type
{
get { return _type; }
set { _type = value; }
}
That is an auto-property and it is the shorthand notation for this:
private string type;
public string Type
{
get { return this.type; }
set { this.type = value; }
}
In C# 6:
It is now possible to declare the auto-properties just as a field:
public string FirstName { get; set; } = "Ropert";
Read-Only Auto-Properties
public string FirstName { get;} = "Ropert";
public string Type { get; set; }
is no different than doing
private string _Type;
public string Type
{
get { return _Type; }
set { _Type = value; }
}
This means that the compiler defines a backing field at runtime. This is the syntax for auto-implemented properties.
More Information: Auto-Implemented Properties
It's an automatically backed property, basically equivalent to:
private string type;
public string Type
{
get{ return type; }
set{ type = value; }
}
These are called auto properties.
http://msdn.microsoft.com/en-us/library/bb384054.aspx
Functionally (and in terms of the compiled IL), they are the same as properties with backing fields.
You can also use a lambda expression
public string Type
{
get => _type;
set => _type = value;
}
With the release of C# 6, you can now do something like this for private properties.
public constructor()
{
myProp = "some value";
}
public string myProp { get; }

Categories

Resources