property: private method or private get/set? - c#

If I want to set my property in a Class private, so it should be only possible to use and set this property in this class, what is the better way? This
public string Name { private get; private set }
or
private string Name { get; set }
hmmm and there is also
private string Name { private get; private set }

It's worth noting that originally, C# wouldn't let you set different accesses on a getter or setter, so the only possible choices were:
public string Name { get; set; }
protected internal string Name { get; set; }
internal string Name { get; set; }
protected string Name { get; set; }
private string Name { get; set; }
(For that matter, you couldn't have automatic properties and always had to do the writing to and from a backing field yourself, but we'll ignore that just because we'll have shorter examples that way).
It is often useful to have different accesses for the two, most often a more restrictive setter than getter, and so the likes of
public string Name { get; private set; }
was introduced.
Now, by extension of that, it would seem logical enough to allow:
public string Name { private get; private set; }
private string Name { private get; private set; }
However, what are these two expressing?
The second isn't too bad, it's just needlessly repetitious. Still though, it's quite likely that some confused thinking got us there (most likely an incomplete refactoring). Good code is as much about expressing what you are doing as making a computer do something (if anything, more so), better to have it express clearly.
Hence if you end up with the likes of { private get; private set; } then it'd likely be worth looking at again and thinking about what you really want to say here. Hurrah for it being a compiler error.
The first case is even worse. It says "this property is public, except for the setter that is private, and the getter that is private". That's not an exception, "it's this thing, except for all the time" is no real expression of anything. Doubly hurrah the compiler for not letting us do it.

Have you tried compiling your examples? Only the middle one will translate.
If you want to specify extra accessibility level keyword, you can only do it on one of the accessors (getter/setter), and that level of the accessor must be more restrictive than the accessibility of the entire property.
Here you see the rules: Restricting Accessor Accessibility

public string Name { get; private set; }
This is what I think you are wanting to do.
There is no point trying to make the get private when the property is public unless you only want your class to see it. In that situation you should use:
private string Name { get; set; }
Update: On second read, you definitely want the second example.

The better way depends on what you want:
public string Name { private get; private set } The property is public but noone can read or wrote to it, except class itself. That is completely useless, so use just
private string Name { get; set }.
In general if you view the property like a couple of methods (which actually is)
private string get_Name() { }
private string set_Name(value) { }
The reason of having a possibility to apply that identifiers to a property get/set becomes evident, I hope.

For a private member, you don't need to define accessors.
Just do this:
private string _name;

It seems like you want
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
this would allow you to access private string Name.

surely enough,
That is the definition of private classifier in OOP: just allow access within methods and scope of the class that owns such private member. Thus if your aim is to disable anyother means of access to a particular member of a class, claiming it as:
private <Type_name> <member_identifier> ;
is the simplest and enough to make it such.

Related

How to pass parameter to class C#?

I have code as below
public class LocalDB
{
public static int e_SessionID;
public static string e_EventName;
public static string e_TimeCreate;
}
in other class:
public static LocalDB newEvent ;
public void something()
{
newEvent.e_SessionID=123;
}
but it is can not pass value.
Problem : You are trying to access the static feilds using instance reference variable newEvent as below:
newEvent.e_SessionID=123;
//^^^Here
Solution : You need to use classname to access the static fields
newEvent.e_SessionID=123;
//^^^Replace with classname LocalDB here
Replace this:
newEvent.e_SessionID = 123;
With this:
LocalDB.e_SessionID = 123;
Why don't you set them up as properties? Have a read of this SO post why prefer properties to public variables
"Fields are considered implementation details of classes and exposing them publicly breaks encapsulation."
public class LocalDB
{
public int SessionID { get; set; }
}
Static methods and variables can only invoke using the class name
and you are trying to call using the class object.
if you want to set the value of e_SessionID set the value using class name as follows
LocalDB.e_SessionID=123;
try to use property instead:
public class LocalDB
{
public int e_SessionID { get; set; }
public string e_EventName { get; set; }
public string e_TimeCreate { get; set; }
}
Prefer instance data to static data.
Static data is effectively global state. Do you have only one event in the lifetime of your program? What if you need to support multithreading? This is object-oriented programming; use objects.
Encapsulate data.
Avoid making fields public. Prefer properties, as others have stated. Note that this allows assigning the creation time at construction (and only then).
Use appropriate types.
If you are storing a date/time value, normally you would use the DateTime class.
Favor immutability.
If you know the values of properties at construction time, set them then and don't allow them to be changed.
Think about names.
Descriptive names matter, especially when you're doing maintenance after six months. I didn't change the name of LocalDB in my example, as I don't know your domain or use case. However, this class looks more like an event than a database to me. Would Event be a better name?
The following example uses C# 6 syntax; earlier versions would need to add private setters and move the initialization to the constructor.
public class LocalDB
{
public LocalDB(int sessionID, string eventName)
{
SessionID = sessionID;
EventName = eventName;
}
public int SessionID { get; }
public string EventName { get; }
public DateTime TimeCreate { get; } = DateTime.UtcNow;
}
public class Other
{
public void DoSomething()
{
NewEvent = new LocalDB(1, "Other Event");
}
public LocalDB NewEvent { get; private set; }
}
A flaw in this example is that the NewEvent property of an Other instance will be null on creation. Avoid nulls where possible. Perhaps this should be a collection of events; not knowing your use case I can't say.

Calling a non-static Variable from another Class

I want to call non-static variable from another class. If I make it static, it affects my other code.
I've two classes Harvest_Client and Harvest_Project.
In my Harvest_Project class I've
public int _client_id{ get; set;}
I'just want to do in Harvest_Client class is,
public int _id = Harvest_Project._client_id;
How should I do this?
Firstly, you should rename the property (it's not a variable) to conform with .NET naming conventions, e.g.
public int ClientId { get; set; }
Next, you need an instance of HarvestProject (post-renaming). Don't just create a new one - you need the right instance, the one whose client ID you're interested in. We can't tell you which one it is - but if you don't already have an instance of HarvestProject to hand, you should work out how you're expecting to specify which client ID you want.
Think of it this way: if I were to ask you "How old is a person?" you'd naturally want to know which person I was talking about. It's exactly the same here.
maybe passing the reference to the class will do what you need:
public class Harvest_Project
{
public string Name { get; set; }
public int clientId { get; set; }
}
public class Harvest_Client
{
private Harvest_Project MyInstance;
private int myid;
public int MyId
{
get
{
return myid;
}
private set
{
MyId = value;
}
}
public Harvest_Client(Harvest_Project cls)
{
MyInstance = cls;
MyId = cls.clientId;//since class reference present no
//need for the property.
//its just here to show if in your
//project you really just need ID
//in this example its redundant
}
}
Depending on what you are trying to do you can make a List of Harvest_Project objects or better a dictionary,if there are various types of "projects" they could be all placed in a dictionary cataloged accordingly to the specified key.
One moment I would like to recommend to take into consideration the following declaration of property public int ClientId {get; private set;"} It allow you to prohibited setting this variable from third party code, if you actually need this. Otherwise you will have ordinary global variable

ASP.NET Web Service DTO Properties vs Public Variables

I have a web service that will return a List where Person is a DTO. Is there any reason I shouldn't define Person like:
public class Person {
public string Name;
public string Email;
}
instead of
public class Person {
private string _name;
public string Name {
get {
return _name;
}
set {
_name = value;
}
}
}
The second version is more verbose, and I can't see any reason public instance variables could be a problem here. Any reason it could be?
Properties are preferred over fields to support
binding; fields cannot be bound
polymorphism; you can't do public virtual string Name;
You can use automatic properties to reduce the verbosity
public class Person {
public string Name { get; set; }
public string Email { get; set; }
}
In general - this is a design decision - see: http://forums.asp.net/t/1233827.aspx
But the DTO implementation is slightly different. Since this is just a DTO and there is no behavior with no set/get property specific implementation the usage you could just as well use the less verbose method. Any implementation change would not require client recompiles since they will be serialized the same way in either case via a service, so your smaller implementation is fine.
Fyi though - if the client is going to use these classes for databinding then they need to be properties in the class. Fields won't be bound.
In addition to all of the other answers, properties allow for validation to be ran when the property is read from or written to. That would take more work to do when using fields.

Protection of acces with Auto-Implemented Properties in C#

A simple example.
alt text http://img19.imageshack.us/img19/1854/51445300.jpg
A have a class TDMReader which is a buldier of TDMFile objects and I am using Auto Implemented Properties f.e.
public string Name
{
get;
set;
}
public Group[] Groups
{
get;
set;
}
What I want to do is to make setter accessible only for TDMReader methods.
In C++ i could have friends methods to access private variables, in Java I could make them in one packet and so access to fields. I have some ideas but with this auto-implemetation is a bit more complicated to do.
Any ideas with a nite solution?:)
Automatic properties have no bearing on this - the same options are available for automatic properties and "manual" properties. You can restrict the access of the setter like this:
// Setter access only to this type and nested types
public string Name { get; private set; }
// Setter access within the assembly
public Group[] Groups { get; internal set; }
etc
... but you can't do it for a single class (unless that class is nested within the declaring type, in which case private would be fine). There's no namespace-restricted access in .NET or C#.
(It's not entirely clear which class the properties are declared in - if they're TdmReader properties, then just make them private. If they're TdmFile properties, you have the problem described above.)
Like this:
public string Name
{
get;
private set;
}
public Group[] Groups
{
get;
private set;
}
By adding the private keyword, the setters will only be accessible by code in the same class. You can also add internal to make it accessible to code in the same project.
Note that exposing an array as a property is extremely poor design.
Instead, you should expose a Collection<Group> or ReadOnlyCollection<Group>, in the System.Collections.ObjectModel namespace.

Should I declare my abstract class's attributes with get; set;?

I'm making a little program that will crawl my hard drive and present a list of file found in a given drive.
My idea is to have a base File class, and implement Picture.cs, Video.cs and Document.cs classes inherited from the File.cs class.
Here's my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SharpLibrary_MediaManager
{
public abstract class File
{
public string name;
public string fileType;
public int size;
public DateTime creationDate;
public DateTime modificationDate;
}
}
Should I declare the short hand code for each attribute like this:
public string name { get; set; }
Any guidance will be helpful. Thank you. :)
Edit:
I mean literally replacing this line:
public string name;
with this line:
public string name { get; set; }
First, "attributes" is not the correct terminolgy here. When you declare a member of a class that has get and/or set defined (formally known as "accessors"), you are defining a property. Properties are a convenient way to expose values of private fields because you can add logic to the getting and setting mechanims.
Second, when you declare a member name as you've done via
public string name { get; set; }
the compiler will expand that into the following:
private string _name;
public string name {
get {
return _name;
}
set {
_name = value;
}
}
That is, the compiler will automatically create a backing field for you and define the accessors. These are called "automatic properties" (for the people)1.
Third, you should never2 publically expose fields. So, if you want to expose the string name as part of your public interface it is better to do it as a property. First, it provides better encapsulation. Second, it can be declared virtual and overridden in dervied classes. Third, you can have custom logic. Fourth, you can have different levels of accessibly between the reading and writing mechanisms on properties but you can not on a field.
Fourth, per accepted naming convetions, public properties should be named with CamelCase so that you should prefer Name instead of name.
1: Sorry, bad joke that I've been waiting a long time to make.
2: Almost never.
You're not describing a short hand syntax for a single item but rather 2 completely different types of members. The get/set version creates a C# Property while the non-get/set version creates a field.
// field
public string name;
// property
public string name {get; set;}
So what you're actually asking here is whether or not you should expose name as a field or a property. The answer is almost certainly property.
If your looking to have these properties, which is what adding the { get; set; } will make the variables, then you should declare the set; part of the property as protected.
So it becomes:
public string name { get; protected set; }
The advantage of this is that you are guaranteeing that the property can only be set by either the base class, or any class that inherits the base class.
As others have suggested, following the C# naming conventions is a good idea and also using properties are highly recommended.
Just to be clear, attributes are means to do declarative programming. They are used to decorate methods, classes, etc. msdn link
If you're asking whether to expose properties rather than public fields, then the answer is Yes.
You should also use PascalCase for the property names rather than camelCase:
public string Name { get; set; }
public string FileType { get; set; }
// etc
As Luke says, all things being equal, properties are preferred to fields.
In addition you may want to change the casing of your fields to match standard C# naming conventions.
Lastly, you might want to avoid the "File" name for your class as you'll probably be using the System.IO namespace which also has a File class. Also, System.IO.FileInfo may already include many of the properties you are planning on creating -- there's no point reinventing the wheel.
I believe another advantage of properties over normal public fields will be ability to override them in the derived class.
class Base
{
public virtual int X
{
get
{
Console.Write("Base GET");
return 10;
}
set
{
Console.Write("Base SET");
}
}
}
class Derived : Base
{
public override int X
{
get
{
Console.Write("Derived GET");
return 10;
}
set
{
Console.Write("Derived SET");
}
}
}
Another useful trick that is applicable while using properties is the ability to modify the modifier of the the derived Properties like changing from Public access to Protected.
Hence in many ways its better to use properties in base class to derive.

Categories

Resources