Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
When to use Methods and Properties in C#?
They can do same thing but when to use both of them.
And also is it possible to set a whole object via C# Property instead of single value.?
A property is more or less what we use to describe different things about a class. They let us define what a class can do and essentially what that class is all about. Consider the following:
namespace Example
{
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public DateTime Birthday { get; set; }
}
}
Name, Age, and Birthday would be considered properties of the Person class. They define what a person is and give us a way to give the class value. A method would then be used to do various things with the properties. You could write a method to get or set the value of a property such as:
public string GetName()
{
return Name;
}
public void SetName(string name)
{
Name = name;
}
However these would be pointless considering the Name property is public meaning it can be accessed whenever we create an instance of the Person class. The above methods would be used if we wanted to set the Name property, but keep it private. Another example of a method would be if we wanted a way to say create a new instance of the person class. By default visual studio will let you instantiate a new Person object like so:
Person jim = new Person();
However we can also write our own "constructor" method to allow us to create a new Person and set it's properties at the same time.
public Person(string name, int age, DateTime birthday)
{
Name = name;
Age = age;
Birthday = birthday;
}
Now we have an easy, streamlined way to instantiate a new Person object which uses a constructor method, and we can create a new Person object like so:
Person jim = new Person("Jim", 25, DateTime.Today);
But the use of methods dont stop there. Since DateTime is the way we represent the Birthday property, we could write a method that could convert a string into the appropriate DateTime.
public DateTime ConvertToDateTime(string date)
{
DateTime temp;
DateTime.TryParse(date, out temp);
return temp
}
Now we can change our constructor to look like this:
public Person(string name, int age, string birthday)
{
Name = name;
Age = age;
Birthday = ConvertToDateTime(birthday);
}
And can instantiate a new Person object like this:
Person jim = new Person("Jim", 25, "1/10/1995");
On a final note, as #vivek nuna said, find a good book! A great one that I've used in previous C# classes would be Murach's book on C#. Also MSDN.com has all the documentation you would need to learn how to code in C#. Try this link to learn more about properties or this link to learn more about methods. Finally, an excellent tutorial I found to learn C# is Scott Lilly's Guide to C#. Not only will you learn the ins and outs of C#, you will get to build a pretty neat and simple text-based RPG!
An proppertie is just a short hand and will create at the background an public get method and a public set
method and a private field to store the value.
// example propertie
public string Name { get; set; }
// at run time it is the same as:
private string Name;
public string GetName(){
return this.Name;
}
public string SetName(string name){
this.Name = name;
}
See Image : the sample class only has an proppertie in code but if you use Reflection to get all the members off the Sample class you will see that at run time these methods are generated but not visable in code.
set_name()
get_name()
'notice the private field Name is not shown because it is private and not visable for the outside, but is genrated.'
Related
This question already has answers here:
What is the difference between a field and a property?
(33 answers)
Closed 9 months ago.
Similar questions has been asked a lot but it still doesn't make sense to me as I am beginner.
here is the link
What is the { get; set; } syntax in C#?
As that answer states
(I will be using age instead of "name" to avoid confusion)
Case 1
public class Genre
{
public int Age { get; set; }
}
and
Case 2:
public class Genre
{
private int age;
public int Age
{
get
{
return this.age;
}
set
{
this.age = value;
}
}
}
Both are the same things.
So for Case 1, where is private age variable?
Does it get declared in the backend.
If Yes, then what name will be assign to it?
Surely not (Age => age) Right?
It feels like,
public int Age { get; set; }
// is same thing as
public int Age;
Now, people have mentioned that one is property another is field. But they both can be used in similar way. So what is the difference on application level?
Can you please give me an example?
It feels like,
public int Age { get; set; }
is same thing as
public int Age;
Absolutely not, the first one is two functions, the setter and the getter, while the second one is a field, an integer. As a physical example of the difference, you can do ref Age in the second example, since it has a physical location in memory, but not in the first example, since it's just functions, it's code.
So for Case 1, where is private age variable? Does it get declared in the backend. If Yes, then what name will be assign to it?
Yeah, it gets generated for you by the compiler with a name you can't declare in C# because it contains invalid characters (that are valid in .Net in general). The actual name doesn't matter, just know that you can't possibly use it or collide with it.
The main difference between the two members in your last code snippet is encapsulation
See the "Encapsulation" part on this page:
https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/tutorials/oop
Hiding the internal state and functionality of an object and only allowing access through a public set of functions.
You asked about what private field gets generated if you use an automatic property. In fact the compiler will generate a private backing field usually called something like k__BackingField or similar.
For example, I created a basic class as follows:
public class Dog
{
public string Name { get; set; }
}
This definitely creates a field in the background, and I can find out by using ILSpy to decompile it and we see the following:
Notice the Name property is there as you'd expect, with its getter and setter. But notice also the k__BackingField.
When we inspect it, it is comprised of the following code:
[CompilerGenerated]
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private string <Name>k__BackingField;
So we can see that there is definitely a private field in the background being generated for the property. We can also confirm that it actually uses that field by inspecting the get_Name getter on the Name property:
[CompilerGenerated]
{
return <Name>k__BackingField;
}
The getter for the Name property indeed returns the private field that was compiler generated for us.
I think what you're stuck on is why we would do this. Basically, if you simply have a public field on a class, you're giving permission for all-and-any other classes to set and get that field without any kind of checks or balances or rules about what goes on when setting or retrieving that value. For small applications that aren't very complex, this won't create an issue for you. But in the future when you're writing bigger applications or libraries, when you want to guarantee certain functionality behaves the same way all the time, this best practice will be necessary.
There is no difference when you use them as simple variables but using a variable as property gives you the ability to perform a check or create an event handler. For example:
private int _onetoten;
public int OneToTen
{
get => _onetoten;
set
{
if ((value > 0) && (value < 11))
{
_onetoten = value;
}
}
}
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I was reading about constructor chaining and I was wondering, if one has a sub instance object inside a class, take for example below, the Course class, how should it be instantiated with the professor object?
public Course(string courseCode, string courseTitle, Professor teacher)
{
if(String.IsNullOrWhiteSpace(courseCode))
{
throw new ArgumentNullException("Course Code Cannot Be Empty");
}
this.courseCode = courseCode;
if(String.IsNullOrWhiteSpace(courseTitle))
{
throw new ArgumentNullException("Course Title Cannot Be Empty");
}
this.courseTitle = courseTitle;
this.prof = Professor.Clone(teacher);
}
public Course(string courseCode, string courseTitle)
:this(courseCode,courseTitle,new Professor())
{
}
Professor class:
public int id {get; private set; }
public string firstName{get; private set;}
public string lastName {get; private set;}
public Professor(int ID, string firstName, string lastname)
{
this.id = ID;
if(String.IsNullOrWhiteSpace(firstName))
{
throw new ArgumentNullException("first name Cannot be Null");
}
this.firstName = firstName;
if(String.IsNullOrWhiteSpace(lastname))
{
throw new ArgumentNullException("last name cannot be null");
}
this.lastName = lastname;
}
The comment in the linked question suggested this:
I think that the best practice when chaining constructors is to call
the constructor with more arguments from the one with less arguments,
providing default values.
My Course class has a professor object as one of the arguments. What should my default values for professor be if the user were to create a course that doesn't have a professor?
public Course(string courseCode, string courseTitle)
:this(courseCode,courseTitle,new Professor())
{
}
in this you shouldnot instantiate new professor() as you dont have any professor.
public Course(string courseCode, string courseTitle)
:this(courseCode,courseTitle,null)
{
}
use this constructor when you want to create course with no professor and assign the professor object only if it is not null in the other constructor.
If a Professor cannot exist without a name or ID, then I would simply not have an overloaded constructor in Course that creates a default professor. You would manage a Course instance with a null Professor as needed.
If they can, and you want a generic professor "John Smith" then I would let the Professor class specify what an "empty" professor means (although I would not recommend this):
public class Professor
{
...
private static Professor _default;
public static Professor Default
{
get
{
if (_default == null)
_default = new Professor(-1, "John", "Smith");
return _default;
}
}
}
And then change your overloaded constructor in Course to:
public Course (string courseCode, string courseTitle)
: this(courseCode, courseTitle, Professor.Default)
This separate of duties will keep your code a little more maintainable, and the singleton instance of a default professor will allow you to do things later like:
if (myProfInstance == Professor.Default)
// insert into DB, for example
What should my default values for professor be if the user were to create a course that doesn't have a professor?
The design approach should provided that answer to what a default professor is when one cannot be directly associated. Otherwise as a developer you need to create that default professor which is simply a bare minimum informational instance which can be handled and updated in future processing in the system.
The idea behind constructor chaining is to simply to organize overloaded constructors to centralize common instantiation actions so they are not repeated.
Supposing I have an Album class :
public class Album
{
public string Name {get; set;}
public string Artist {get; set;}
public int Year {get; set;}
public Album()
{ }
public Album(string name, string artist, int year)
{
this.Name = name;
this.Artist = artist;
this.Year = year;
}
}
When I want to assign data to an object of type Album, what is the difference between the next 2 approaches :
Via Constructor
var albumData = new Album("Albumius", "Artistus", 2013);
or when instantiating
var albumData = new Album
{
Name = "Albumius",
Artist = "Artistus",
Year = 2013
};
Both approaches call a constructor, they just call different ones. This code:
var albumData = new Album
{
Name = "Albumius",
Artist = "Artistus",
Year = 2013
};
is syntactic shorthand for this equivalent code:
var albumData = new Album();
albumData.Name = "Albumius";
albumData.Artist = "Artistus";
albumData.Year = 2013;
The two are almost identical after compilation (close enough for nearly all intents and purposes). So if the parameterless constructor wasn't public:
public Album() { }
then you wouldn't be able to use the object initializer at all anyway. So the main question isn't which to use when initializing the object, but which constructor(s) the object exposes in the first place. If the object exposes two constructors (like the one in your example), then one can assume that both ways are equally valid for constructing an object.
Sometimes objects don't expose parameterless constructors because they require certain values for construction. Though in cases like that you can still use the initializer syntax for other values. For example, suppose you have these constructors on your object:
private Album() { }
public Album(string name)
{
this.Name = name;
}
Since the parameterless constructor is private, you can't use that. But you can use the other one and still make use of the initializer syntax:
var albumData = new Album("Albumius")
{
Artist = "Artistus",
Year = 2013
};
The post-compilation result would then be identical to:
var albumData = new Album("Albumius");
albumData.Artist = "Artistus";
albumData.Year = 2013;
Object initializers are cool because they allow you to set up a class inline. The tradeoff is that your class cannot be immutable. Consider:
public class Album
{
// Note that we make the setter 'private'
public string Name { get; private set; }
public string Artist { get; private set; }
public int Year { get; private set; }
public Album(string name, string artist, int year)
{
this.Name = name;
this.Artist = artist;
this.Year = year;
}
}
If the class is defined this way, it means that there isn't really an easy way to modify the contents of the class after it has been constructed. Immutability has benefits. When something is immutable, it is MUCH easier to determine that it's correct. After all, if it can't be modified after construction, then there is no way for it to ever be 'wrong' (once you've determined that it's structure is correct). When you create anonymous classes, such as:
new {
Name = "Some Name",
Artist = "Some Artist",
Year = 1994
};
the compiler will automatically create an immutable class (that is, anonymous classes cannot be modified after construction), because immutability is just that useful. Most C++/Java style guides often encourage making members const(C++) or final (Java) for just this reason. Bigger applications are just much easier to verify when there are fewer moving parts.
That all being said, there are situations when you want to be able quickly modify the structure of your class. Let's say I have a tool that I want to set up:
public void Configure(ConfigurationSetup setup);
and I have a class that has a number of members such as:
class ConfigurationSetup {
public String Name { get; set; }
public String Location { get; set; }
public Int32 Size { get; set; }
public DateTime Time { get; set; }
// ... and some other configuration stuff...
}
Using object initializer syntax is useful when I want to configure some combination of properties, but not neccesarily all of them at once. For example if I just want to configure the Name and Location, I can just do:
ConfigurationSetup setup = new ConfigurationSetup {
Name = "Some Name",
Location = "San Jose"
};
and this allows me to set up some combination without having to define a new constructor for every possibly permutation.
On the whole, I would argue that making your classes immutable will save you a great deal of development time in the long run, but having object initializer syntax makes setting up certain configuration permutations much easier.
Second approach is object initializer in C#
Object initializers let you assign values to any accessible fields or
properties of an object at creation time without having to
explicitly invoke a constructor.
The first approach
var albumData = new Album("Albumius", "Artistus", 2013);
explicitly calls the constructor, whereas in second approach constructor call is implicit. With object initializer you can leave out some properties as well. Like:
var albumData = new Album
{
Name = "Albumius",
};
Object initializer would translate into something like:
var albumData;
var temp = new Album();
temp.Name = "Albumius";
temp.Artist = "Artistus";
temp.Year = 2013;
albumData = temp;
Why it uses a temporary object (in debug mode) is answered here by Jon Skeet.
As far as advantages for both approaches are concerned, IMO, object initializer would be easier to use specially if you don't want to initialize all the fields. As far as performance difference is concerned, I don't think there would any since object initializer calls the parameter less constructor and then assign the properties. Even if there is going to be performance difference it should be negligible.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I was thinking about language constructs and how when we talk about classes and objects in Object oriented languages we draw comparisons to real world. Like when people talk of Inheritance people would quote an example of Parent and Children. One thing that i don't find in OO languages that i know , mainly C, C++, C#, is that they don't have a mechanism to declare a property as mandatory. What i mean by that is I cannot define a class called human and say that face, hands and lets say eye are mandatory property of my class. By having that construct i can enforce that anyone who is using my class need to set those properties before using my class. If user forgets to set those properties then i should get an compile time error.
Just wanted to see community thoughts on that.
Here is reason why i had asked above question:
When i build my user controls, i want to make sure that users should set some of the properties in their code when they use my control. For example, lets say i build a customer user control that would be used by other developers in my team. Some of the properties that i have exposed are: "CustomerId", "FirstName", "LastName", "Address1", "City", "State" and ZipCode. Now i want to make sure that any consumer of my control should set "CustomerId". Using Constructor to enforce that the value is set is a way but it will throw a run time exception plus how would user call that constructor from .cs file without dynamically creating the control and adding it to control collection.
You can do that, with a DDD principle: create a class with a private default constructor, and a public constructor that accept required parameters and validate its values. If a value is invalid, throw an exception so that the object cannot be created. Properties could also have private setters instead of public setters.
You can also create a 'Mandatory' attribute and put those on top of the properties that are mandatory; and have a mechanism that checks this based on whether a property has been decorated with the attribute or not.
Example:
public class BlogEntry
{
private BlogEntry() {}
public BlogEntry(string title, string body)
{
LastModifiedDate = DateTime.Now;
Title = title;
Body = body;
var blogEntryValidator = new BlogEntryValidator();
blogEntryValidator.ValidateAndThrow(this);
}
public int Id { get; private set; }
public string Title { get; private set; }
public string Body { get; private set; }
public DateTime? LastPublishDate { get; private set; }
public DateTime LastModifiedDate { get; private set; }
public virtual ICollection<Comment> Comments { get; private set; }
public void Publish()
{
LastPublishDate = DateTime.Now;
}
public void Unpublish()
{
LastPublishDate = null;
}
public void Modify(string title, string body)
{
Title = title;
Body = body;
LastModifiedDate = DateTime.Now;
}
public Comment AddComment(string commentText, string emailAddress, string name)
{
var comment = new Comment(this, commentText, emailAddress, name);
if (Comments == null) Comments = new List<Comment>();
Comments.Add(comment);
return comment;
}
public void RemoveComment(Comment comment)
{
Comments.Remove(comment);
}
}
public class Comment
{
private Comment() {}
public Comment(BlogEntry blogEntry, string name, string emailAddress, string commentText)
{
BlogEntry = blogEntry;
Name = name;
EmailAddress = emailAddress;
CommentText = commentText;
DateWritten = DateTime.Now;
var commentValidator = new CommentValidator();
commentValidator.ValidateAndThrow(this);
}
public int Id { get; private set; }
public string Name { get; private set; }
public string EmailAddress { get; private set; }
public string CommentText { get; private set; }
public DateTime DateWritten { get; private set; }
public BlogEntry BlogEntry { get; private set; }
}
Yes, C++ and C# allow for this via constructors.
class A
{
public:
A(int x, int y, int z)
: _x(x_, _y(y), _z(z) {}
private:
int _x;
int _y;
int _z;
};
You cannot create an instance of A without providing values for _x, _y, and _z.
The reason is that state needed to fulfil class invariants should be provided during object construction, so you should provide values of 'mandatory' properties as constructor parameters. Your question is based on false assumption that an object is characterized by setting state with properties. This is wrong for a handful of reasons, some of which are:
many, if not most OO languages have no properties: Java, C++,...
what you use is only formally an object, it is actually a plain record and it is not very object oriented, same as e.g. C++ struct without methods (see notes at the bottom about setters vs methods)
Allowing the client to create instances of the objects which are only later set up with correct values for mandatory state is sure-fire way to spend many hours in company of debugger.
Let's take some User with invariant that first and last name must always be set.
class User {
public User(string first, string last) { ... }
public User(string first, string last, uint age) : this(first, last) { ... }
}
// client code:
var user = new User("john", "doe");
var user2 = new User("Clint", "Eastwood", 82);
Compiler ensures that no one can instantiate the object without fulfilling the invariants.
Now compare it with your approach:
class User {
public User(string first, string last) { ... }
public User(uint age) { ... }
[Mandatory] public string FirstName { get; set; }
[Mandatory] public string LastName { get; set; }
}
// client code:
var actor = new User(82); // << invalid
actor.FirstName = "Clint";
actor.LastName = "Eastwood"; // << valid
This approach results in more code and allows for a period of time (between << invalid and << valid) where your object is not in a valid state. What if some of property setters throw an exception? You are left with broken object instance floating around. Do you expect the compiler to also verify that code in the setter can not throw? Do you think it is even possible? Besides that, every client which instantiates User instances must check what are the mandatory properties and make sure to set all of them. This effectively breaks encapsulation.
IMO, property setters should be rare, unlike getters. I believe that in such a class you should not have setters for FirstName/LastName, only getters. Instead there should be a method SetName(string first, string last) if you really want to allow name changing. Here's why:
// lets rename actor
actor.FirstName = "John";
actor.LastName = "Wayne";
If the last line throws, you are left with John Eastwood, an actor I have never heard about. With actor.SetName("John", "Wayne") this can't happen.
Additionally, what about property which have dependency in order you specify them, e.g.
obj.ErrorCode = 123; // imagine that error code must be != 0
obj.ErrorMsg = "foo"; // in order to be allowed to set error code
Would you also introduce attributes for that instead of having obj.SetErrorInfo(123, "foo")? This makes it obvious that properties break encapsulation as the order is caused by the implementation detail, unlike with method call.
Quite often, in languages like C#, required state or dependencies is provided in constructor while optional state can be set through properties. However, it is not properties or inheritance which make a language object-oriented.
Sure you can! Just use parameters in constructor to denote which are mandatory.
public class Human
{
public Face Face { get; set; }
public Hand Hand { get; set; }
public Human(Face face, Hand hand) {} etc...
}
In this instance, you cannot use the private constructor, so these properties are essentially "mandatory" in order to use the Human class.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
When do you use the “this” keyword?
Can anyone explain me the "this" reference? when we use this ? with a simple example.
When you use this inside a class, you're refering to the current instance: to the instance of that class.
public class Person {
private string firstName;
private string lastName;
public Person(string firstName, string lastName) {
//How could you set the first name passed in the constructor to the local variable if both have the same?
this.firstName = firstName;
this.lastName = lastName;
}
//...
}
In the above example, this.firstName is refering to the field firstName of the current instance of the class Person, and firstName (the right part of the assignment) refers to the variable defined in the scope of the constructor.
So when you do:
Person me = new Person("Oscar", "Mederos")
this refers to the instance Person instance me.
Edit:
As this refers to the class instance, cannot be used inside static classes.
this is used (too) to define indexers in your classes, like in arrays: a[0], a["John"],...
this is a scope identifier. It is used within an object's instance methods to identify behaviors and states that belong to an instance of the class.
Nowadays-fashionable Fluent APIs use this extensively. Basically it's used to get hold of a reference to the current instance.
here's a simple example
public class AnObject
{
public Guid Id { get; private set;}
public DateTime Created {get; private set; }
public AnObject()
{
Created = DateTime.Now;
Id = Guid.NewGuid();
}
public void PrintToConsole()
{
Console.WriteLine("I am an object with id {0} and I was created at {1}", this.Id, this.Created); //note that the the 'this' keyword is redundant
}
}
public Main(string[] args)
{
var obj = new AnObject();
obj.PrintToConsole();
}