Modify class members value [closed] - c#

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 7 years ago.
Improve this question
I have a class and constructor in order to initiate it like this:
public class Merchant
{
public int userID;
public int clubID;
public short categoryID;
public string posTerminalID;
public string name;
public double score;
public double subClubSharePercent;
public double simClubSharePercent;
public bool isActive;
public string modificationDatetime;
public Merchant()
{
}
public Merchant(int uID, int cID, Int16 aID, string pID, string n, double s, double sSp, double sCp, Boolean iA, DateTime dt)
{
Date da = new Date();
this.userID = uID;
this.clubID = cID;
this.categoryID = aID;
this.posTerminalID = pID;
this.name = n;
this.score = s;
this.subClubSharePercent = sSp;
this.simClubSharePercent = sCp;
this.isActive = iA;
this.modificationDatetime = da;
}
}
how can i modify the class members value:
Use the constructor method again?
Create modify class and call it?
what is the differences between initializing class with constructor and syntax?
thank you.

Dan Field has definitely given you an adequate answer, but I figured I'd chime in with a few tidbits as well.
Constructors are useful for setting variables that otherwise could never be set by the developer. These include private fields, private functions, and private properties.
You've declared many public fields. You know they're fields because there is no 'setter' or 'getter' function. Properties, however, are defined by having the getter and setter functions. Setters and getters are not just a C# phenomenon, they're useful in many object-oriented languages.
In C#, public properties can be set by the programmer whenever necessary - initializing public properties through the constructor (with a few exceptions) isn't necessarily useful. That said, there are patterns where requiring every field to be passed into the constructor means that the object can't exist without all of its info. In your case, that's not apparently a concern as you have a parameterless constructor in public Merchant().
C# also allows for object initialization right in its syntax, without the need to pass in every property through parameters in the constructor.
Consider the difference here:
//Constructor with all parameters
public Merchant(int uID, int cID, Int16 aID, string pID, string n, double s, double sSp,
double sCp, Boolean iA, DateTime dt) {
Date da = new Date();
this.userID = uID;
this.clubID = cID;
this.categoryID = aID;
this.posTerminalID = pID;
this.name = n;
this.score = s;
this.subClubSharePercent = sSp;
this.simClubSharePercent = sCp;
this.isActive = iA;
this.modificationDatetime = da;
}
//Code using it
Merchant merchant = new Merchant(uID, cID, aID, pID, n, s, sSp, sCp, iA, dt);
versus
//Constructor with no parameters
public Merchant( ) { }
//Code using it
Merchant merchant = new Merchant( ) {
userID = uID,
categoryID = aID,
isActive = iA,
modificationDateTime = da
};
The main differences being that with the first method, you're enforcing all parameters to be present. The second method, however, gives the user more flexibility to instantiate only what they want/need.

You can only call a class constructor once. Once the object is constructed, it's constructed and that's just it (leaving aside any weird attempts to invoke the code in a constructor through reflection).
If you want to be able to use a single method to change the values of the class after it's been constructed, you'll have to write a method to do so (perhaps you don't want someone to change only one member variable at a time? running validations against the variables that, for thread-safety reasons, you wan tto run all at once?).
If you don't want outside objects to be able to modify the values of the class, you should probably make those public properties have a private set, e.g.:
public bool isActive { get; private set; }
This will make it clear that property can be read but not written outside the class itself, and prevent a non-member from modifying the variable.
If you want the properties to be settable only by a constructor (and not even a member method can change them), mark them readonly. But realize that to get new values here, you'll have to make a completely new object (i.e. new Merchant(param, param, param....).

Related

C# Methods and Properties [closed]

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.'

Naming Conventions with Class properties in Methods [closed]

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 currently have this source of code as an example:
class Person
{
public Person create(string _name, int _uid)
{
return new Person()
{
name = _name,
uid = _uid,
};
}
public int uid;
public string name;
}
I know it isn't the biggest of deals but I work on projects that have multiple developers meaning conventions are important.
On the official .NET naming conventions documentation, it states do-not use symbols however, this method is for the use of adding to a List<Person> People = new List<Person>(); and is called like so:
People.Add(Person.create("Example", 1));
I have looked at sources like:
C# Property Examples
Which they use a prefix _ to declare its only temp to get or set a value which I then copied.
My question is, does this follow the .NET naming conventions or how can I keep it similar to the property names that currently exist?
The convention is to use camelCase for parameter names, so they should be named name and uid. It doesn't matter whether they're temporary, or long-lived, whether you use them and discard them or store them in a field.
While on the subject of naming conventions, methods should be named using PascalCase, so I would rename create to Create.
Your public fields should actually be properties (see Jon Skeet's Why Properties Matter for a complete explanation why), and should also be named using PascalCase.
public int Uid { get; private set; }
public string Name { get; private set; }
Finally, I'd question why the Person class has a non-static method to create an instance of Person. joe.Create("mike", 123) doesn't make much sense to me.
MSDN has a nice list of naming conventions here.
The only thing it's missing is using a leading underscore + snakeCase for private fields (e.g. _myAge). This is not endorsed by Microsoft, although it's a widely used convention. It's also encouraged by some refactoring tools such as ReSharper.
Take a look at the readonly keyword
IMHO prefix "_" for any variables is not common for c#
code source https://msdn.microsoft.com/de-de/library/acdd6hb7.aspx
public class ReadOnlyTest
{
class SampleClass
{
public int x;
// Initialize a readonly field
public readonly int y = 25;
public readonly int z;
public SampleClass()
{
// Initialize a readonly instance field
z = 24;
}
public SampleClass(int p1, int p2, int p3)
{
x = p1;
y = p2;
z = p3;
}
}
static void Main()
{
SampleClass p1 = new SampleClass(11, 21, 32); // OK
Console.WriteLine("p1: x={0}, y={1}, z={2}", p1.x, p1.y, p1.z);
SampleClass p2 = new SampleClass();
p2.x = 55; // OK
Console.WriteLine("p2: x={0}, y={1}, z={2}", p2.x, p2.y, p2.z);
}
}
/*
Output:
p1: x=11, y=21, z=32
p2: x=55, y=25, z=24
*/

Does a property need to be explicitly initialized? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Does a property need to be explicitly initialized like so:
public DeviceSettings ds{ get; private set; } = new DeviceSettings();
Or is it OK to keep it this way?
public class MyDevice
{
public MyDevice(string serial, int patientid)
{
}
public DeviceSettings ds{ get; private set; } //no initialization needed?
}
In your first example ds is set to a new instance of DeviceSettings, in your 2nd example ds is set to default(DeviceSettings) which if that type is a class will be null.
If you wish to do it the 2nd way and your type is a class you will need to add the assignment in the constructor
public class MyDevice
{
public MyDevice(string serial, int patientid)
{
ds = new DeviceSettings();
}
public DeviceSettings ds{ get; private set; }
}
Properties don't need to be initialized at the time you create a new instance of your class. That depends mostly of your business logic.
Property Initializers can help you when you want to initialize your property with a default value,eg:
private DateTime CreateOn { get; } = DateTime.UtcNow;
Which is translated to something like this:
private readonly createOn= DateTime.UtcNow;
public DateTime CreateOn
{
get
{
return createOn;
}
}
That is a property that is going to remain immutable after its initialization.
As #ScottChamberlain pointed out in his answer, you can initialize an auto-implemented property in the constructor of your class. That is a good place to initialize your property if this depends of an external value that is passed as parameter to the constructor, eg:
public class Product
{
private PriceCalculator Calculator {get;set;}
public decimal Price{get {return Calculator.GetPrice();}}
public Product(int factor)
{
Calculator=new PriceCalculator(factor);
}
}
public DeviceSettings ds{ get; private set; } = new DeviceSettings();
That syntax was introduced only in C# 6.0. So it's completely fine do not initialize it. In that case, it will get default value (depends on DeviceSettings, is it value or reference type)
No initialization are needed for instantiate your class.
If you're going to use property, you need to initialize it to have a correct value (it will mainly be null, because null is default value in many cases, except if your redefine it or use a struct). You can do it with C#6 syntaxic sugar as your first example, or in constructor.

How do I access the nested Class? [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 8 years ago.
I have the following three classes defined.
public class FrequencyRecord
{
public double Frequency;
public int Duration;
}
public class EntryRecord
{
public string Name;
public Boolean Status;
public long TotalTime;
public FrequencyRecord[] FreqTime = new FrequencyRecord[25];
public string Description;
}
public class Salv7Profile
{
public string Version;
public string SoftVersion;
public string Name;
public DateTime CreateDate;
public DateTime LastModDate;
public int Count;
public EntryRecord[] Entries = new EntryRecord[99];
public int Type;
}
Then I create an instance:
public static Salv7Profile IntProfile = new Salv7Profile();
Assigning a value to:
IntProfile.Name = "Peter";
works fine, But if I try:
IntProfile.Entries[1].Name = "Peter";
It throws an error: [System.NullReferenceException] "Object reference not set to an instance of an object."}
Being a novice at C#, how do I access the nested Entries class?
The problem is that you've created an array, but that array is just full of null references to start with. You'd need something like:
EntryRecord record = new EntryRecord();
record.Name = "Peter";
IntProfile.Entries[1] = record;
to replace the array element with a reference to the newly-created EntryRecord.
It would almost certainly be better if you changed Entries to be a List<EntryRecord> though, and just used:
EntryRecord record = new EntryRecord();
record.Name = "Peter";
IntProfile.Entries.Add(record);
or more briefly, using an object initialzier:
IntProfile.Entries.Add(new EntryRecord { Name = "Peter" });
I would also strongly recommend against having public fields; use properties instead, and consider making your types immutable if you can.
(I'd encourage to think about whether you really need the IntProfile field to be static, too... static fields imply global state, which is harder to test and reason about.)

How to ensure certain class members are initialized before use [closed]

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.

Categories

Resources