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; }
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.
With mongodb c# drivers we can map a private member like this
cm.MapField("_sessionTimes").SetElementName("SessionTimes");
And this populates SessionTimes in MongoDb.
This is a private member, it isn't a backing field of a public property.
Is there a way to populate this field back while getting the entity form MongoDb?
My class has AddSessionTime method, ideally I would like to use this method to populate that private field while mongodb drivers deserializing my entity.
By the way the type of _sessionTimes is
IDictionary<DayOfWeek, SessionTime>
SessionTime is a simple class:
public class SessionTime
{
public TimeSpan Start { get; set; }
public TimeSpan End { get; set; }
}
And AddSessionTime is a method in my class:
public void AddSessionTime (DayOfWeek dayOfWeek, SessionTime sessionTime)
{
if (_sessionTimes.ContainsKey(dayOfWeek))
{
_sessionTimes[dayOfWeek] = sessionTime;
}
else
{
_sessionTimes.Add(dayOfWeek, sessionTime);
}
}
Thanks.
I have three classes which have many common properties, so I generated a base class from which they inherit:
public class CommonConfig
{
public TimeSpan Period1 { get; private set; }
public TimeSpan Period2 { get; private set; }
public TimeSpan Period3 { get; private set; }
};
public class Config1 : CommonConfig
{
public long count1 {get; private set; }
}
public class Config2 : CommonConfig
{
public long count2 {get; private set; }
}
I am not sure that I want to make CommonConfig to be public. Is it possible to keep it private but still make something that allows usage like below.
Config1 c1;
TimeSpan ts1 = c1.Period1;
No you can not, as to be able to access to the property of that class, you need to specify it public, and you can not specify private a class which properties are public .
Config1 c1;
TimeSpan ts1 = c1.Period1; // THIS PROPERTY HS TO BE PUBLIC
and if you
//MISMATCH BETWEEN CLASS AND ITS PROPERTIES ACCESS MODIFIERS
private class CommonConfig {
public TimeSpan Period1 { get; private set; }
public TimeSpan Period2 { get; private set; }
public TimeSpan Period3 { get; private set; }
}
and even more, you will get compiler error:
Elements defined in a namespace cannot be explicitly declared as
private, protected, or protected internal
As defining a class on the "top" level (on level of the namespace) you have to declare it public. If you want to hide it, you have to declare that class inside another class.
You cannot make a class private, internal is the most restrictive possible modifier for a non nested class.
Also you cannot have the access for descendant classes less restrictive than the parent class, so you have to stick with public for CommonConfig.
No You can not make it as private.
you can not access private class with public property.
you must specify Public class
If your aim is to prevent usage of the class CommonConfig directly, you could mark the class CommonConfig as abstract and also the properties within it (as required).
That way, though the class would be visible but the only way to use it would be via Config1 or Config2 .
See this for more details.
How about
public class CommonConfig
{
public TimeSpan Period1 {get; protected set;}
{
You could also make the whole attribute protected if needed...
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)
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;}