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)
Related
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.
Im not sure because in Java getter/setter are looking a little bit different but whats the "c# way" to code this stuff?
Option a.)
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
private int time;
public int Time
{
get { return time; }
set { time = value; }
}
b.)
private string _name;
private int _time;
public string name
{
get { return _name; }
set { _name = value; }
}
public int time
{
get { return _time; }
set { _time = value; }
}
c.)
public string name {get; set;}
public int time {get; set;}
Ok there are some examples. What would look better? Should I write all the private variable declarations first then the properties or should I group my variable and property declaration next to each other.
How about d, following .NET naming conventions:
public string Name { get; set; }
public int Time { get; set; } // Odd type for time, admittedly...
Don't bother writing the property manually yourself unless you do something non-trivial in it.
If you do write the property implementation manually, it's up to you how you name the private variable. Personally I'd use:
private string name;
public string Name
{
get { /* whatever */ }
set { /* whatever */ }
}
... but if you want to use underscores, that's your prerogative.
As for ordering of members - that's even more your own choice. Assuming you're working with a team, talk with the team and see what the local convention is.
If you don't need access to the underlying backing fields, then auto-properties are the suggested way which is (C). However, according to .NET naming convention they should be PascalCase.
public string Name { get; set; }
public int Time { get; set; }
The first two are just naming convensions that you should choose based on the company/dev group or your own decision.
The third case is the short way of decalring the same property, where the actual field will be generated by runtime itself.
Short Pros: it's short and easy.
Short cons: Can not put something inside geter/setter, can not put breakpoint in Visual Studio...
Hope this helps.
In your specific case (no logic on getter or setter) the best option is C (with a small change on properties names to follow C# standards)
public string Name {get; set;}
public int Time {get; set;}
Depends on the case, when you define the fields an underscore character is used, and if you just need a simple getter/setter there is no need to define the fields yourself because the compiler will define them for you in the background.
I would go for the option, most others already posted.
public string Name {get; set;}
public int Time {get; set;}
Note, that you can make change protection-level on the setter and getter individually, e.g.
public string Name {get; protected set;}
protected int Time {get; private set;}
You can only use a higher protection than applied to the hole property.
public string Name {get; set;}
public int Time {get; set;}
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
This question already has answers here:
Collection of generic types
(10 answers)
Closed 7 years ago.
I have an object (form) which contains a collection (.Fields) which I want to contain instances of a generic class (FormField).
The FormField, simply, is defined as such:
public class FormField<T>
{
private Form Form;
public T Value { get; set; }
public string Name { get; set; }
public void Process()
{
// do something
}
public FormField(Form form, string name, T value)
{
this.Name = name;
this.Value = value;
this.Form = form;
}
}
This allows me to have FormField, FormField etc. and that part works great.
What I want is a collection of "Formfields" regardless of the type, but I am forced into defining a type (it seems) such as:
public class Form
{
string Code { get; set; }
string Title { get; set; }
int Year { get; set; }
Guid ClientID { get; set; }
ICollection<FormField<int>> Fields { get; set; }
}
What, I think, I want is an interface that allows me to abstract the type information and thus type the collection as instances of (for exxample) IFormField not FormField<>
But I can't see how to define this without strongly typing the collection in the interface...
Any help (including any alternative solutions!) would be greatly appreciated!
Thanks, Ben
Here's some code to complete Jon's answer:
public interface IFormField
{
string Name { get; set; }
object Value { get; set; }
}
public class FormField<T> : IFormField
{
private Form Form;
public T Value { get; set; }
public string Name { get; set; }
public void Process()
{
// do something
}
public FormField(Form form, string name, T value)
{
this.Name = name;
this.Value = value;
this.Form = form;
}
// Explicit implementation of IFormField.Value
object IFormField.Value
{
get { return this.Value; }
set { this.Value = (T)value; }
}
}
And in your form:
ICollection<IFormField> Fields { get; set; }
Create a non-generic interface or base class, which probably includes everything FormField does except the type-specific bits. Then you can have an ICollection<IFormField>. Obviously you won't be able to use this in a strongly-typed way, in terms of the type of field being used - but you can use all the non-type-specific bits of it (e.g. the name and the form).
Another option (an alternative to Jon's answer) is to apply the adapter pattern, which can be useful when:
you are unable to modify the type, and can thus not define a base-type for it.
or, there is a need to expose 'type-specific bits' (as Jon put it).
When you want to expose type-specific bits, you effectively have to create a non-generic wrapper. A short example:
class NonGenericWrapper<T> : IAdaptor
{
private readonly Adaptee<T> _adaptee;
public NonGenericWrapper(Adaptee<T> adaptee)
{
_adaptee = adaptee;
}
public object Value
{
get { return _adaptee.Value; }
set { _adaptee.Value = (T) value; }
}
}
Implementing this non-generic behavior in a base-type would effectively break the Liskov substitution principle, which is why I prefer the wrapper approach as I also argue in my blog post.
I have read about how in ASP.NET 3.5 you can declare properties in C#
public DateTime DisplayDate
{
get;
}
instead of
private DateTime _displayDate
public DateTime DisplayDate
{
get {return _displayDate;}
}
like this post explains.
My question is, within the class, how do I access the private variable?
For example instead of this
public MyClass(DateTime myDisplayDate)
{ _displayDate = myDisplayDate; }
What should I assign to?
Is it the public property?
public MyClass(DateTime myDisplayDate)
{ DisplayDate = myDisplayDate; }
Is this Correct?
public DateTime DisplayDate
{
get; private set;
}
public MyClass(DateTime myDisplayDate)
{
this.DisplayDate = myDisplayDate;
}
Automatic Properties like this (which aren't limited to ASP.NET) are there so you don't have to deal with the private field. If you want to set the property's value, use the property itself and add a private setter (so only your class can set it)
public DateTime DisplayDate
{
get;
private set;
}
You always need to declare both the getter and the setter with c# 3.0 automatic properties - see the other answers - the trick is to mark the setter as private.
public Foo { get; private set; }