C# data model, are there any differences between using these form? - c#

I'm going to build my MVC Web Application and I created my data models.
I found online many ways to compile a data model code. This is easiest one, using only public properties:
public class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
But I also found a version using a private variable and a public properies, like this:
public class Person
{
private int id;
private string firstName;
private string lastName;
public int Id { get { return id; } set { id = value; } }
public string FirstName { get { return firstName; } set { firstName = value; } }
public string LastName { get { return lastName; } set { lastName = value; } }
}
What is the difference between these two data models?
When is more advisable using the first one or the second one?

This is the same like asking: what is a difference bwteen auto properties and normal properties.
Auto properties:
easy creation (less to type)
internal field is generated for you automatically by compiler
Not possible to debug (set a break point inside the property)
Normal properties
Sligtly more code to type
Easy to debug
More code can be injected inside get and set

If first example compiler will create private field for every automatic property itself, but they behave exactly the same. More info on MSDN
I would suggest second approach as you have more control how property works, but there is nothing wrong in using first one.

The fiest block you have are auto-properties, and under the hood the c# will be compiled similar to the second block, so in this case there is no difference. Take a look at these posts here:
C# 3.0 auto-properties - useful or not?
What are Automatic Properties in C# and what is their purpose?
Any reason to use auto-implemented properties over manual implemented properties?
If you were implementing the INotifyPropertyChanged interface, then you would need to use the traditional way as you would be interacting with the property in the setter, see example...
http://msdn.microsoft.com/en-us/library/ms743695.aspx

Related

How can I use C# predefined get and set with a private field?

Usually I would build my field like this:
private string name;
public void setName(string name){
this.name = name;
}
public string getName(){
return name
}
that works perfectly when doing this: string myString = object.getName() or object.setName("Alex").
However, I thought I might give the inbuilt C# functions a try.
So I did this:
private string name { get; set; }
however, that won't work at all. When I try to access the field with object.name, I can't even access it due to private restriction.
Did I misunderstand something about these predefined get/sets?
If I had to mark every field as public, why should I even use getters or setters? I could access the field like in the snippet above without get and set?
You're mixing up way too many things - you might want to read a book on C#, really. It usually takes some time to get rid of some of the preconceptions from your old programming language - but you really do want to do that; even Java and C# are incredibly different when you go beyond the surface appearance.
First, nothing is forcing you to use auto-properties. If you want to use properties while keeping your manual backing fields, you can simply use this:
private string name;
public string Name { get { return name; } set { name = value; } }
If you do want to use auto-properties, you have to understand that the backing field is hidden - you're only declaring the property; and you want that property to be public (though you can also use accessibility modifiers on the individual get/set "methods", e.g. private set). But the field is never accessible - it's "always" behind the property.
To mirror your original code, this is what you want:
public string Name { get; set; }
Only if you ever need to move away from using auto-properties (that is, you need to add some logic to either the getter or the setter), you will have to reintroduce the manual backing field, and stop using auto-properties - see the first code sample in my answer.
Did I misunderstand something about these predefined get/sets?
Yes, you did. The property itself has to be public. If you're using auto-properties, then you can't do any validation since the backing field is compiler generated. If you want to actually do something with the value before, you can use a property with a backing field:
private string name;
public string Name
{
get { return name; }
set
{
if (string.IsNullOrEmpty(name))
throw new ArgumentException("name cannot be null");
name = value
}
}
Because this:
public string Name { get; set; }
Generated a backing field like this:
[DebuggerBrowsable(DebuggerBrowsableState.Never), CompilerGenerated]
private string <Name>k__BackingField;
public string Name
{
[CompilerGenerated]
get
{
return this.<Name>k__BackingField;
}
[CompilerGenerated]
set
{
this.<Name>k__BackingField = value;
}
}
Just do
public string Name { get; set; }
That compiles down to a private field with an unspeakable name, and a public property. That public property has a public get method and a public set method.
Seems to be exactly what you want.
Alternatively, use
public string Name { get; private set; }
Your get method will be public as before, but the set method will be private then.
As of C# 6 (Visual Studio 2015), you can even do
public string Name { get; }
In that case, there is no set method, not even a private one, but you can assign to the underlying field through the property in the constructor.
Did I misunderstand something about these predefined get/sets?
Yes, a bit.
If I had to mark every field as public, why should I even use getters or setters? I could access the field like in the snippet above without get and set?
This is the part that you're missing. The syntax you are talking about it called an auto-implemented property. That is, when you write:
public string Name { get; set; }
the C# compiler generates a private field, getter, and setter behind the scenes for you. You can see them if you look at the metadata for your class, and get access to them via reflection. They have the exact same names as the getter or setter you would write yourself (typically get_Name and set_Name). The only difference is, you didn't have to write them.
The reason to do this is because most getter/setter pairs only exist to add a layer of abstraction over a private field, and consist of a single return name or name = value line of code. If that's all you want, you may as well let the compiler write it for you.
However, if you ever needed something more complex, you can manually implement the getter and setter yourself, and callers won't know the difference. In other words, if you change:
public string Name { get; set; }
to
private string name;
public string Name
{
get
{
return name;
}
set
{
name = value;
RecalculateSomeStuff();
}
}
then the metadata for your class is identical. Anyone using your class does not have to even be recompiled to pick up the new setter, because as far as the callers are concerned, they're still called set_Name directly.
What the others want to tell you is that you should deferentiate between fields (privates) and properties (public) (is not a rule but a convention)
private string name;
public string Name{ get; set;}
// you can acces to the property:
var objectName = YourObject.Name
// and set the value of your property:
YourObject.Name = "whatever"
First of all the equivalent of your code is
private string _name;
public string Name
{
get {return _name;}
set { _name = value; }
}
OR simply
public string Name { get; set; }
To define the accessibility level of the "Name" field, you put the access modifiers (public, protected, etc.) before get or set
Example
//Read only properties
public string Name
{
get {return _name;}
private set { _name = value; }
}
To have more details and see difference between public fieal and public property see Difference between Auto - Implemented Properties and normal public member
PS :
To write this in Visual studio you can use snippet, type prop keyword then tab key or propfull and press tab key. press tab key our shift+tab to navigate between highlighted fields

Encapsulation C# newbie

New to C#, and I understand that encapsulation is just a way of "protecting data". But I am still unclear. I thought that the point of get and set accessors were to add tests within those methods to check to see if parameters meet certain criteria, before allowing an external function to get and set anything, like this:
private string myName;
public string MyName;// this is a property, speical to c#, which sets the backing field.
private string myName = "mary";// the backing field.
public string MyName // this is a property, which sets/gets the backing field.
{
get
{
return myName;
}
set
{
if (value != "Silly Woman"){
myName = value;
}
}
}
But I've been seeing code in c# which just looks like this:
public string MyName { get; set; }
Why would you just have a get and set with nothing in there, - isn't that the same as just declaring your private backing field public? If you can just get and set it from outside, why wouldn't you just do it directly?
Indeed, creating an auto-property as follows:
public string Name { get; set; }
is identical to building a property backed by a field:
private string _name;
public string Name {
get { return _name; }
set { _name = value; }
}
The point of these properties is not to hide data. As you observed, they don't do this. Instead, these properties can do other stuff instead of just working with a field:
public string Name {
get { return _name; }
set { if (value == null) throw new Exception("GTFO!"); _name = value; }
}
Another thing is, you can make properties virtual:
public virtual string Name { get; set; }
which, if overridden, can provide different results and behaviours in a derived class.
By using public string MyName { get; set; }, you leave an ability to change its logic later without the need to recompile/change other code that uses your property.
For example, if you are making a library and v1 uses a field and v2 uses a property, applications that work with v1 will not work with v2 without recompilation (and, potentially, code changes if they are written in some .NET language that has different syntax for accessing fields).
Another important difference is in serialization scenarios -- a lot of them do not support fields. Also any interface that requires a property can not be implemented without using one, but depending on interface it may not be required to do any additional checks/logic in it.
It makes it easier to add logic later. If you have a class that has a public field that you want to change to a property, you have to recompile everything that uses your class. That's a key point that I didn't understand initially.
If you have a class:
public class MyClass
{
public string MyString;
}
You could access the value like this:
var myClass = new MyClass();
string s = myClass.MyString;
Now change that to a property:
public class MyClass
{
public string MyString { get; set; }
}
How is it accessed? The exact same way:
var myClass = new MyClass();
string s = myClass.MyString;
So no big deal, right? Well, actually....
Properties are actually compiled into getter and setter methods:
get_MyString() and set_MyString(string value)
So the two methods do produce different compiled code. Now if all your code that uses this class is in the same project, is not as big a deal, because it will all be compiled together. But if you have an API library that you've distributed, it can be a much bigger deal to update.
Because it is easier to change the Code if you want to add the checks/tests later on.
Especially if you have many inheritance and many classes in your code it is very hard to change the implementation from a public variable to a public Property.
Moreover you can add to the get and set within the property different attributes, e.g. if you are using reflection. The get and set of the property are internally different methods. If you have just a public variable /field it is not possible to added different properties to the different access ways.
Yeah, but you can easily change it to:
public string MyName { get; private set; }
Plus, properties are used in other scenarios, like DataContracts and Serialization... so, this is a nice feature... (Mostly, syntactic sugar. I think) EDIT: I take that back.. you can apply virtual to it, so it's not the same

Is there a way to intercept setters and getters in C#?

In both Ruby and PHP (and I guess other languages as well) there are some utility methods that are called whenever a property is set. ( *instance_variable_set* for Ruby, *__set* for PHP).
So, let's say I have a C# class like this:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
Now, let's say that if any property setter from the Person class is called, I want to call another method first, and then continue with the default behaviour of the setter, and the same applies for the property setters.
Is this possible?
Edit:
I want to do this without defining a backing field.
Not generally; a few options though;
inherit from ContextBoundObject - which does allow this, but at a performance cost
write an explicit property (i.e. with a backing field), and add a utility method call manually
look at compile-time weavers, such as PostSharp - generally by spotting an attribute or similar
look at runtime code generators, as offered by some DI/IoC tools (and some other "decorator" based tools) - which either decorate or subclass your object to add the extra code
It is possible to do directly in the property body itself, but then you need to use a proper backing field instead of auto-implemented properties.
private string firstName;
public string FirstName
{
get { return firstName;}
set
{
if(check(value))
{
firstName = value;
}
}
}
Even with auto-implemented properties you get a backing field - this is generated by the compiler and you don't have direct access to it.
Edit:
Seeing as you don't want a backing field, you have other options - using an AOP tool such as PostSharp could help with that.
You will have to write the properties in full to achieve this.
I know this has been properly answered but I'll include an example to show you the syntax to achieve what you want:
public class Person
{
private
public string FirstName
{
get
{
return _firstName;
}
set
{
// see how we can call a method below? or any code for that matter..
_firstName = SanitizeName(value);
}
}
}
Are you in a position to rewrite your class to implement an interface? If so, Unity's interface interceptor might give you what you need. If an interface is not an option then that link also documents Unity's type and instance interceptors.
Not out of the box. You would need to insert code into each properties setter and getter, either manually or automatically using IL rewriting.
When you want to do it manually, you can't use automatic properties any more.
When you want to do it automatically, have a look at AOP.
Yes, of course...
In your example you are using automatic properties, without a backing field.... You just need to create a backing field for your property, and then you can do what you want in the setter and getter.
example:
private string firstName;
public string FirstName
{
get { return firstName; }
set { doMethod(); firstName = value;}
}
Mocking frameworks can do this, as well as IoC libraries like Unity. The only other way to do such a thing would be to use IL-rewriting (as previously mentioned).
You cant use automatic properties. You would have to dinfe the property out the old fashion way with a backing field and call the method manually.
public class Person
{
private string _FirstName;
public string FirstName
{
get
{
return _FirstName;
}
set
{
SomeMethod();
_FirstName = value;
}
}
private void SomeMethod()
{
//do something
}
}
As far as I know, you have to use a backing field and put the call to the other method inside the setter thusly:
public class Person {
private string firstName;
private string lastName;
public string FirstName {
set {
DoSomeStuff();
firstName = value;
}
get { return firstName; }
}
public string LastName {
set {
DoSomeStuff();
lastName = value;
}
get { return lastName; }
}
}

What is the { get; set; } syntax in C#?

I am learning ASP.NET MVC and I can read English documents, but I don't really understand what is happening in this code:
public class Genre
{
public string Name { get; set; }
}
What does this mean: { get; set; }?
It's a so-called auto property, and is essentially a shorthand for the following (similar code will be generated by the compiler):
private string name;
public string Name
{
get
{
return this.name;
}
set
{
this.name = value;
}
}
So as I understand it { get; set; } is an "auto property" which just like #Klaus and #Brandon said is shorthand for writing a property with a "backing field." So in this case:
public class Genre
{
private string name; // This is the backing field
public string Name // This is your property
{
get => name;
set => name = value;
}
}
However if you're like me - about an hour or so ago - you don't really understand what properties and accessors are, and you don't have the best understanding of some basic terminologies either. MSDN is a great tool for learning stuff like this but it's not always easy to understand for beginners. So I'm gonna try to explain this more in-depth here.
get and set are accessors, meaning they're able to access data and info in private fields (usually from a backing field) and usually do so from public properties (as you can see in the above example).
There's no denying that the above statement is pretty confusing, so let's go into some examples. Let's say this code is referring to genres of music. So within the class Genre, we're going to want different genres of music. Let's say we want to have 3 genres: Hip Hop, Rock, and Country. To do this we would use the name of the Class to create new instances of that class.
Genre g1 = new Genre(); //Here we're creating a new instance of the class "Genre"
//called g1. We'll create as many as we need (3)
Genre g2 = new Genre();
Genre g3 = new Genre();
//Note the () following new Genre. I believe that's essential since we're creating a
//new instance of a class (Like I said, I'm a beginner so I can't tell you exactly why
//it's there but I do know it's essential)
Now that we've created the instances of the Genre class we can set the genre names using the 'Name' property that was set way up above.
public string Name //Again, this is the 'Name' property
{ get; set; } //And this is the shorthand version the process we're doing right now
We can set the name of 'g1' to Hip Hop by writing the following
g1.Name = "Hip Hop";
What's happening here is sort of complex. Like I said before, get and set access information from private fields that you otherwise wouldn't be able to access. get can only read information from that private field and return it. set can only write information in that private field. But by having a property with both get and set we're able do both of those functions. And by writing g1.Name = "Hip Hop"; we are specifically using the set function from our Name property
set uses an implicit variable called value. Basically what this means is any time you see "value" within set, it's referring to a variable; the "value" variable. When we write g1.Name = we're using the = to pass in the value variable which in this case is "Hip Hop". So you can essentially think of it like this:
public class g1 //We've created an instance of the Genre Class called "g1"
{
private string name;
public string Name
{
get => name;
set => name = "Hip Hop"; //instead of 'value', "Hip Hop" is written because
//'value' in 'g1' was set to "Hip Hop" by previously
//writing 'g1.Name = "Hip Hop"'
}
}
It's Important to note that the above example isn't actually written in the code. It's more of a hypothetical code that represents what's going on in the background.
So now that we've set the Name of the g1 instance of Genre, I believe we can get the name by writing
console.WriteLine (g1.Name); //This uses the 'get' function from our 'Name' Property
//and returns the field 'name' which we just set to
//"Hip Hop"
and if we ran this we would get "Hip Hop" in our console.
So for the purpose of this explanation I'll complete the example with outputs as well
using System;
public class Genre
{
public string Name { get; set; }
}
public class MainClass
{
public static void Main()
{
Genre g1 = new Genre();
Genre g2 = new Genre();
Genre g3 = new Genre();
g1.Name = "Hip Hop";
g2.Name = "Rock";
g3.Name = "Country";
Console.WriteLine ("Genres: {0}, {1}, {2}", g1.Name, g2.Name, g3.Name);
}
}
Output:
"Genres: Hip Hop, Rock, Country"
Those are automatic properties
Basically another way of writing a property with a backing field.
public class Genre
{
private string _name;
public string Name
{
get => _name;
set => _name = value;
}
}
It is a shortcut to expose data members as public so that you don't need to explicitly create a private data members. C# will creates a private data member for you.
You could just make your data members public without using this shortcut but then if you decided to change the implementation of the data member to have some logic then you would need to break the interface. So in short it is a shortcut to create more flexible code.
This is the short way of doing this:
public class Genre
{
private string _name;
public string Name
{
get => _name;
set => _name = value;
}
}
Basically, it's a shortcut of:
class Genre{
private string genre;
public string getGenre() {
return this.genre;
}
public void setGenre(string theGenre) {
this.genre = theGenre;
}
}
//In Main method
genre g1 = new Genre();
g1.setGenre("Female");
g1.getGenre(); //Female
Basically it helps to protect your data. Consider this example without setters and getter and the same one with them.
Without setters and getters
Class Student
using System;
using System.Collections.Generic;
using System.Text;
namespace MyFirstProject
{
class Student
{
public string name;
public string gender;
public Student(string cName, string cGender)
{
name = cName;
gender= cGender;
}
}
}
In Main
Student s = new Student("Some name", "Superman"); //Gender is superman, It works but it is meaningless
Console.WriteLine(s.Gender);
With setters and getters
using System;
using System.Collections.Generic;
using System.Text;
namespace MyFirstProject
{
class Student
{
public string name;
private string gender;
public Student(string cName, string cGender)
{
name = cName;
Gender = cGender;
}
public string Gender
{
get { return gender; }
set
{
if (value == "Male" || value == "Female" || value == "Other")
{
gender = value;
}
else
{
throw new ArgumentException("Invalid value supplied");
}
}
}
}
}
In Main:
Student s = new Student("somename", "Other"); // Here you can set only those three values otherwise it throws ArgumentException.
Console.WriteLine(s.Gender);
Its an auto-implemented property for C#.
The get/set pattern provides a structure that allows logic to be added during the setting ('set') or retrieval ('get') of a property instance of an instantiated class, which can be useful when some instantiation logic is required for the property.
A property can have a 'get' accessor only, which is done in order to make that property read-only
When implementing a get/set pattern, an intermediate variable is used as a container into which a value can be placed and a value extracted. The intermediate variable is usually prefixed with an underscore.
this intermediate variable is private in order to ensure that it can only be accessed via its get/set calls. See the answer from Brandon, as his answer demonstrates the most commonly used syntax conventions for implementing get/set.
They are the accessors for the public property Name.
You would use them to get/set the value of that property in an instance of Genre.
That is an Auto-Implemented Property. It's basically a shorthand way of creating properties for a class in C#, without having to define private variables for them. They are normally used when no extra logic is required when getting or setting the value of a variable.
You can read more on MSDN's Auto-Implemented Properties Programming Guide.
This mean that if you create a variable of type Genre, you will be able to access the variable as a property
Genre oG = new Genre();
oG.Name = "Test";
In the Visual Studio, if you define a property X in a class and you want to use this class only as a type, after building your project you will get a warning that says "Field X is never assigned to, and will always has its default value".
By adding a { get; set; } to X property, you will not get this warning.
In addition in Visual Studio 2013 and upper versions, by adding { get; set; } you are able to see all references to that property.
Its basically a shorthand. You can write public string Name { get; set; } like in many examples, but you can also write it:
private string _name;
public string Name
{
get { return _name; }
set { _name = value ; } // value is a special keyword here
}
Why it is used? It can be used to filter access to a property, for example you don't want names to include numbers.
Let me give you an example:
private class Person {
private int _age; // Person._age = 25; will throw an error
public int Age{
get { return _age; } // example: Console.WriteLine(Person.Age);
set {
if ( value >= 0) {
_age = value; } // valid example: Person.Age = 25;
}
}
}
Officially its called Auto-Implemented Properties and its good habit to read the (programming guide).
I would also recommend tutorial video C# Properties: Why use "get" and "set".
Such { get; set; } syntax is called automatic properties, C# 3.0 syntax
You must use Visual C# 2008 / csc v3.5 or above to compile.
But you can compile output that targets as low as .NET Framework 2.0 (no runtime or classes required to support this feature).
Get set are access modifiers to property.
Get reads the property field.
Set sets the property value.
Get is like Read-only access.
Set is like Write-only access.
To use the property as read write both get and set must be used.
Get is invoked when the property appears on the right-hand side (RHS)
Set is invoked when the property appears on the left-hand side (LHS)
of '=' symbol
For an auto-implemented property, the backing field works behind the scene and not visible.
Example:
public string Log { get; set; }
Whereas for a non auto-implemented property the backing field is upfront, visible as a private scoped variable.
Example:
private string log;
public string Log
{
get => log;
set => log = value;
}
Also, it is worth noted here is the 'getter' and 'setter' can use the different 'backing field'
A property is a like a layer that separates the private variable from other members of a class. From outside world it feels like a property is just a field, a property can be accessed using .Property
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullName => $"{FirstName} {LastName}";
}
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullName { get { return $"{FirstName} {LastName}"; } }
}
FullName is a Property. The one with arrow is a shortcut. From outside world, we can access FullName like this:
var person = new Person();
Console.WriteLine(person.FullName);
Callers do not care about how you implemented the FullName. But inside the class you can change FullName whatever you want.
Check out Microsoft Documentation for more detailed explanation:
https://learn.microsoft.com/en-us/dotnet/csharp/properties
Define the Private variables
Inside the Constructor and load the data
I have created Constant and load the data from constant to Selected List class.
public class GridModel
{
private IEnumerable<SelectList> selectList;
private IEnumerable<SelectList> Roles;
public GridModel()
{
selectList = from PageSizes e in Enum.GetValues(typeof(PageSizes))
select( new SelectList()
{
Id = (int)e,
Name = e.ToString()
});
Roles= from Userroles e in Enum.GetValues(typeof(Userroles))
select (new SelectList()
{
Id = (int)e,
Name = e.ToString()
});
}
public IEnumerable<SelectList> Pagesizelist { get { return this.selectList; } set { this.selectList = value; } }
public IEnumerable<SelectList> RoleList { get { return this.Roles; } set { this.Roles = value; } }
public IEnumerable<SelectList> StatusList { get; set; }
}
Properties are functions that are used to encapsulate data, and allow additional code to be executed every time a value is retrieved or modified.
C# unlike C++, VB.Net or Objective-C doesn’t have a single keyword for declaring properties, instead it uses two keywords (get/set) to give a much abbreviated syntax for declaring the functions.
But it is quite common to have properties, not because you want to run additional code when data is retrieved or modified, but because either you MIGHT want to do so in the future or there is a contract saying this value has to be a exposed as a property (C# does not allow exposing data as fields via interfaces). Which means that even the abbreviated syntax for the functions is more verbose than needed. Realizing this, the language designers decided to shorten the syntax even further for this typical use case, and added “auto” properties that don’t require anything more than the bare minimum, to wit, the enclosing braces, and either of the two keywords (separated by a semicolon when using both).
In VB.Net, the syntax for these “auto” properties is the same length as in c# —- Property X as String vs string X {get; set;}, 20 characters in both cases. It achieves such succinctness because it actually requires 3 keyword under the normal case, and in the case of auto properties can do without 2 of them.
Removing any more from either, and either a new keyword would have had to be added, or significance attached to symbols or white space.

Basic C# property question

In C# do properties need to reference private member variables, or can I just declare the properties and use them directly in the class code?
If the former is the best practice, then does that rule out using C# property short-hand? I.e.
public string FirstName { get; set; }
Properties, when implemented like this:
public string FirstName { get; set; }
Automatically create a private member variable (the compiler does this for you), so you don't have to worry about it. This will behave exactly the same as if you do:
private string firstName;
public string FirstName {
get { return firstName; }
set { firstName = value; }
}
There is no reason not to use the automatic properties ( { get; set; } ). The provide the same advantages as making your own private member variable.
In addition, if you later decide you need to do extra processing (for example, if you decide to implement INotifyPropertyChanged in your property setter), you can add this without changing your public API, but putting a backing field in manually.
You don't need properties to access private fields but in general it is considered best practice.
And you can use auto-properties (short hand) untill you need to add more functionality to a property, like validation. Changing it to a 'real' property is always a non-breaking change.
Properties created like this
public String Caption{ get; set; }
this will be compiled as
[CompilerGenerated]
private string <Caption>k__BackingField;
public string Caption
{
[CompilerGenerated]
get
{
return this.<Caption>k__BackingField;
}
[CompilerGenerated]
set
{
this.<Caption>k__BackingField = value;
}
}
The above code is extracted after compilation using reflector tool.
They do not need to reference private member variables. You can use them directly in the class.
Properties do not need to reference private member variables. It is best practice, though, to have them do so. You can think of properties as methods if it makes it easier to understand. You can run code inside of them. You can return whatever you want. You can call methods and use private member variables. You can even simply return a constant.
I use private member variables in almost all cases. It allows me to create a readonly property, or to provide some rules to those outside my class of getting or setting properties that my class doesn't have to follow.
To add on to Reed's answer, inside of your code (within the class itself) the member functions should adhere to this and actually use the Property rather then the actual private member. For instance if you had this:
public string FirstName { get; set; }
And you had a strange method called public char GetFirstLetter() that returned the first letter in a person's first name you'd want to do it like this:
public char GetFirstLetter()
{
return FirstName[0];
}
Instead of actually using your private variable. When you set a property a programmer may have written code to set it in a particular manner. So it only makes sense to simply use that property within your class methods.
C# can reference private variables as in:
public class A
{
private string _b;
public string B
{
get { return _b; }
set { _b = value; }
}
}
The get;set; designation is automatic properties which when compiled will generate the private variable for you, as a way to make it easy to setup your code.
Using properties is the best way to provide a method of control and security to the attributes in a class, always keep the attributes private if possible.
if you use like
public string FirstName { get; set; }
compiler will automatically adds getters and setters for this property automatically.it not a bad practice.
Here is the proof
if you declare
private string firstName;
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
like this also compiler will takes it as
so its not ruled out... :)

Categories