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;}
Related
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;
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.
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)
Let's say I have a class from a 3rd-party, which is a data-model. It has perhaps 100 properties (some with public setters and getters, others with public getters but private setters). Let's call this class ContosoEmployeeModel
I want to facade this class with an interface (INavigationItem, which has Name and DBID properties) to allow it to be used in my application (it's a PowerShell provider, but that's not important right now). However, it also needs to be usable as a ContosoEmployeeModel.
My initial implementation looked like this:
public class ContosoEmployeeModel
{
// Note this class is not under my control. I'm supplied
// an instance of it that I have to work with.
public DateTime EmployeeDateOfBirth { get; set; }
// and 99 other properties.
}
public class FacadedEmployeeModel : ContosoEmployeeModel, INavigationItem
{
private ContosoEmployeeModel model;
public FacadedEmployeeModel(ContosoEmployeeModel model)
{
this.model = model;
}
// INavigationItem properties
string INavigationItem.Name { get; set;}
int INavigationItem.DBID { get; set;}
// ContosoEmployeeModel properties
public DateTime EmployeeDateOfBirth
{
get { return this.model.EmployeeDateOfBirth; }
set { this.model.EmployeeDateOfBirth = value; }
}
// And now write 99 more properties that look like this :-(
}
However, it's clear that this will involve writing a huge amount of boilerplate code to expose all the properties , and I'd rather avoid this if I can. I can T4 code-generate this code in a partial class, and will do if there aren't any better ideas, but I though I'd ask here to see if anyone had any better ideas using some super wizzy bit of C# magic
Please note - the API I use to obtain the ContosoEmployeeModel can only return a ContosoEmployeeModel - I can't extend it to return a FacededEmployeeModel, so wrapping the model is the only solution I can think of - I'm happy to be corrected though :)
The other approach may be suitable for you is to use AutoMapper to map base class to your facade here is sample code:
class Program
{
static void Main(string[] args)
{
var model = new Model { Count = 123, Date = DateTime.Now, Name = "Some name" };
Mapper.CreateMap<Model, FacadeForModel>();
var mappedObject = AutoMapper.Mapper.Map<FacadeForModel>(model);
Console.WriteLine(mappedObject);
Console.ReadLine();
}
class Model
{
public string Name { get; set; }
public DateTime Date { get; set; }
public int Count { get; set; }
}
interface INavigationItem
{
int Id { get; set; }
string OtherProp { get; set; }
}
class FacadeForModel : Model, INavigationItem
{
public int Id { get; set; }
public string OtherProp { get; set; }
}
}
Resharper allows the creation of "delegating members", which copies the interface of a contained object onto the containing object and tunnels the method calls/property access through to the contained object.
http://www.jetbrains.com/resharper/webhelp/Code_Generation__Delegating_Members.html
Once you've done that, you can then extract an interface on your proxy class.
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