Declaring Persons with Constructor [closed] - c#

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 9 years ago.
Improve this question
I have a class (People) that defines people, and contains this members:
public int socialSecurityNr;
public string name;
public int age;
public double heigth;
public double weigth;
public string Nationality;
public int shoeSize;
Now, I want to create a constructor for the class that inserts the value of the social security number and sets the rest of the fields to null values. I tried this:
public People(int socialSecurity, string NAME, string AGE, double HEIGTH)
{
socialSecurity= socialSecurityNr;
this.name = null;
this.age = null;
this.weigth = 0;
}
Is this the right way to declare a constructor that should set the Social Security number and set the rest to null?
(The thing is that when I create a new Person, I should be able to give that person a name, age, height etc.)

You can't declare an int as null. You can make it nullable though by doing it a nullable int like this:
public int? age;

Just include de ss number in the constructor. By default all other reference type will be null. The errors happen because value types, like double and int can't be null.

If you have not the the entire values for instantiate a person class you can use Nullable type, with "?" at the definition.
For sample :
public class Person
{
public int socialSecurityNr;
public string name;
public int age;
public double heigth;
public Person(int p_socialSecurityNr, string p_name, int? p_age, double? p_heigth)
{
this.socialSecurityNr = p_socialSecurityNr; // Can't be null
if (p_name != null)
{
this.name = p_name;
}
if (p_age != null)
{
this.age = p_age.Value;
}
if (p_heigth != null)
{
this.heigth = p_heigth.Value;
}
}
}

Related

Class property setter is not throwing expected exception c# [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 1 year ago.
Improve this question
I have a Class called "person" that takes name, age and weight properties. I am trying to make sure that when a person object is instantiated, the name property is at least 5 characters and contains a space. I want to throw a new exception if not.
Here is the setter for name prop:
public string Name
{
get
{
return this.name;
}
set
{
if (value.Length < 5 || value.Contains(" ") == false)
{
throw new ArgumentException("Invalid");
}
else
{
this.name = value;
}
}
}
I've created a couple person objects with invalid data and no exception is thrown. My plan is to use a try catch block in the constructor to handle the exception. Am I going about this the wrong way?
There is no user input in this program, it is just an assignment. We are supposed to instantiate some person objects with invalid data to test our exception handling code. Here is an example of an object that should throw an exception:
person p1 = new person("hi", 26, 165);
here is the class constructor:
public person(string Name, string Age, double Weight)
{
this.name = Name;
this.weight = Weight;
try
{
this.age = int.Parse(Age);
}
catch (FormatException)
{
WriteLine("Age must be an integer number. Age set to 0 by default.");
this.age = 0;
}
}
This is building on a previous assignment where we had to take age as a string value and try to parse it.
You are not calling the Name setter in the constructor, so the property setter is not being called. Use
this.Name = Name;
in the constructor to call the property setter.
Also, a few nitpicks, but I would also use :
if (value.Length < 5 || !value.Contains(" "))
instead of == false, and give a better error message:
throw new ArgumentException("Name must be at least 5 characters and must contain a space", "Name");
your constructor should be like thus
public person(string name, string age, double weight)
{
this.Name= name;
this.Age= age;
this.Weight = weight;
}
Then the setters will invoke and exception will be thrown if needed
You Name property is not thrown an exception , since you don't call setter.
Use this
Name=name;
and it is a common practice to use _ for private members, so use _name instead of name in your Name getter/setter.
IMHO it is a bad idea use exceptions to depict code flow. So you don't need _name, defined Name as
public string Name {get; set; }
and move a validation to a constructor,
public person(string name, string age, double weight)
{
Weigt=weght;
if (name.Length < 5 || !value.Contains(" ") )
Consodle. WriteLine ($"Name {name} is not valid. Must be at least 5 characters and contain a space");
else Name = name
if (Double.TryParse(age, out number)) Age=age;
else
Console.WriteLine($"Unable to parse age {age}.");
}

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

Modify class members value [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 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....).

Chaining Constructors [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am trying to better understand chaining of constructors in C# and I have run into the following issue.
class Item
{
private string _name;
private string _category;
private int _sku;
private double _price;
// default values
public Item()
{
_name = "";
_category = "Sale Item";
_sku = 123;
_price = 1.99;
}
public Item(string name, double price) : this()
{
this._name = name;
this._price = price;
}
public Item(string name, string category, int sku, double price)
{
this._name = name;
this._category = category;
this._sku = sku;
this._price = price;
}
public string Name
{
get { return this._name; }
}
public string Category
{
get { return this._category; }
}
public int SKU
{
get { return this._sku; }
public double Price
{
get { return this._price; }
}
}
My idea was to use the parameterless constructor to set default values and use the parametrized constructors to only change those values which need to be updated.
Unfortunately this does not work. The code does not compile. The error message is 1729: there is no constructor that takes 2 arguments. I realize that this is not how constructors are normally chained but I do not understand why this fails to compile as the parameterless constructor Item() is called first before the second constructor Item(string name, double price) is called.
Any insight and sugegstions would be greatly appreciated.
Nothing wrong with the chaining constructors per se, the error you get is related to other code instantiating it with 2 specific paramaters which their is no specific constructor provided.
You need to add another 2 parameter constructor which matches that signature to fix that error.

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

Categories

Resources