It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
This is basically my first attempt to understand the classes in C#. I've went through several tutorials on the internet, but the thing I'm missing the most and what I haven't found anywhere yet, is a simple good example.
I have some idea how my basic program should look like and I would appreciate your help:
using System;
namespace Introduction_to_classes
{
class Person
{
int Age;
string Name;
int DateOfBirth()
{
return 2013 - Age;
}
}
class Program
{
public static void Main()
{
Person Mother = new Person(35, Alice);
Person Son = new Person(12, Johny);
Mother.Name = "Lucy"; // Just changing the value afterwards
if(Mother.Age > Son.Age)
{
int year = Mother.DateOfBirth();
Console.WriteLine("Mom was born in {0}.", year);
}
Console.ReadLine();
}
}
}
It's just an idea, it definitely doesn't work. But more than anything else it would help me if you can correct it to the working example...
class Person
{
public int Age { get; set; }
public string Name { get; set; }
public Person(int age, string name)
{
Age = age;
Name = name;
}
public int DateOfBirth()
{
return 2013 - Age;
}
}
class Program
{
public static void Main()
{
Person Mother = new Person(35, "Alice");
Person Son = new Person(12, "Johny");
Mother.Name = "Lucy"; // Just changing the value afterwards
if (Mother.Age > Son.Age)
{
int year = Mother.DateOfBirth();
Console.WriteLine("Mom was born in {0}.", year);
}
}
}
Some useful links: properties, constructor
using System;
namespace Introduction_to_classes {
class Person {
public int Age;
public string Name;
public int DateOfBirth() {
return 2013-Age;
}
}
class Program {
public static void Main() {
Person Mother=new Person {
Age=35,
Name="Alice"
};
Person Son=new Person {
Age=12,
Name="Johny"
};
Mother.Name="Lucy"; // Just changing the value afterwards
if(Mother.Age>Son.Age) {
int year=Mother.DateOfBirth();
Console.WriteLine("Mom was born in {0}.", year);
}
Console.ReadLine();
}
}
}
The problem is that you're referring to a constructor that doesn't exist:
Person Mother = new Person(35, Alice);
The first argument here is an int, the second should be a string as far as I understand. But a string literal should be marked with double quotes, so that line should be:
Person Mother = new Person(35, "Alice");
Same for the following line.
Now you probably want a constructor that takes types of these arguments and you want to save these values to the new object, I assume. So, add this in your Person class:
public Person(int a, string n)
{
this.Age = a;
this.Name = n;
}
And, finally, you should make your Age and Name fields accessible to the other class, by marking them internal or public:
public int Age;
public string Name;
After that, you should be good to go.
First of all: new Person(35, "Alice") implies that class Person defines a constructor public Person(int age, string name). Alternatively, you'll have to call new Person() { Age = 35, Name = "Alice" } which only works as long as you have not defined a constructor, or have defined a constructor that takes 0 arguments, such as public Person() (notice how I put "Alice" within quotation marks? That's because you didn't define a string called Alice, so Alice is an unknown object)
Next we have Mother.Name = "Lucy", which won't work, because Name is not discoverable. The class Person does define a Name, but since you didn't specify an access modifier, such as public or private, class Program doesn't even know it exists and thus cannot access it. So you have to use public string Name instead of string Name. It is also considered to be good style to always specify your access modifier. The same applies to public int Age and public int DateOfBirth() as well.
To know more about access modifiers refer to http://msdn.microsoft.com/en-us/library/ms173121.aspx
Related
This question already has answers here:
When do you use the "this" keyword? [closed]
(31 answers)
Closed 3 years ago.
Noobie here, but I was wondering why and when would I need to use "this" keyword to access the Promote method in GoldenCustomer when I can already access it since GoldenCustomer is derived from the base class Customer which already has this method? Saw "this" being used in an online course but could't help but wonder.
Edit:
No my question isnt a duplicate because the other question doesnt answer when and if it is necessary to use "this" during inheritance.
class Program
{
static void Main(string[] args)
{
Customer customer = new Customer();
customer.Promote();
GoldCustomer goldCustomer = new GoldCustomer();
goldCustomer.OfferVoucher();
}
}
public class GoldCustomer : Customer{
public void OfferVoucher(){
this.Promote(); //why is this used here?
}
}
public class Customer{
public int Id { get; set; }
public string Name { get; set; }
public void Promote(){
int rating = CalculateRating(excludeOrders: true);
if (rating == 0)
System.Console.WriteLine("Promoted to level 1");
else
System.Console.WriteLine("Promoted to level 2");
}
private int CalculateRating(bool excludeOrders){
return 0;
}
}
The most common uses is when a variable in a method/function has the same name as another class-level variable.
In this case, using the this keyword will tell the compiler that you're referring to the class's variable.
For example:
public class Customer
{
public string Name { get; set; }
Public Customer (string Name, string Id)
{
this.Name = Name; // "this.Name" is class's Name while "Name" is the function's parameter.
}
}
MSDN Doc for other uses and further reading
Also, a small side-note: ID should always be stored as a string since int has the maximum value of 2147483648, and ID's are treated as a string anyway (you never use math-related functions on it like Id++ or Id = Id * 2 for example).
I'm obviously referring to state-issued IDs like "6480255197" and not "1", "2" and so on.
I have a class called Person which has properties Name, DateOfBirthand Age. Name and DateOfBirth are supplied when class instance is created but I want the Age property to be computed automatically as soon as the instance of class is created. I know how to do it using Parametrized Constructor but as I am trying to understand the power of Properties, I attempted following program but it is not giving expected output.
using System;
namespace Property
{
class Person
{
#region private varaibles
private int _age;
#endregion
#region properties
public string Name { get; set; }
public DateTime DateOfBirth { get; set; }
public int Age
{
get { return _age; }
set { _age = (DateTime.Now - DateOfBirth).Days / 365; }
}
#endregion properties
}
class Program
{
static void Main(string[] args)
{
Person P = new Person() { Name = "Merin Nakarmi", DateOfBirth = new DateTime(1990, 1, 12) };
Console.WriteLine("{0}, whose Date Of Birth is {1} is {2} years old!", P.Name, P.DateOfBirth, P.Age);
}
}
}
The output I am getting is
I am expecting age to be 28. Help please.
It seems you need a readonly age, if that's the case, you don't need to set anything in Age property, simply do:
public int Age
{
get {
return DateTime.Now.Year - DateOfBirth.Year;
}
}
You may also want to have a look here and read a bit more on properties.
By the way as also #John pointed out concerning the correct calculation of the age(meaning taking leap years into account, you may want to have a look here)
You are trying to read the property without setting it. So you can do both of these things in code like
get { return ((DateTime.Now - DateOfBirth).Days / 365); }
I'm currently looking into inheritance and polymorphism and I'm a bit confused about where you'd want to create a Person object of type Student?
assuming the following code:
class Person
{
public string Name { get; set; }
public int Age { get; set; }
public string Gender { get; set; }
}
class Student : Person
{
public int YearOfStudy { get; set; }
public string Course { get; set; }
public string PredictedGrade { get; set; }
}
Now looking online, there are a few options here in terms of creating an object:
Person p = new Person();
Student s = new Student();
Person ps = new Student();
The first objects allows me to set name, age and gender, while the second allows me to set those 3, as well as yearsOfStudy, course and predictedGrade. But I'm unsure of what the third object allows me to do? I can still set all 6 parameters, however I can only use the attributes set in the Person class? Any explanation on the correct usage of the third object would be appreciated.
Thanks
Don't think of this as Person ps = new Student() yet.
The real benefit is being able to abstract common code for all types of Person. So your methods may take in a Person because that's all it needs and will work with any person type you create such as Janitor, Teacher, etc.
var myStudent = new Student()
VerifyAge(myStudent);
VerifyYearOfStudy(myStudent);
public bool VerifyAge(Person person)
{
return person.Age < 200;
}
public bool VerifyYearOfStudy(Student student)
{
return student.YearOfStudy <= DateTime.Now.Year;
}
To clear up some confusion the only time you ever really declare the base in a method is when you want to actually denote that this variable is only meant to be used as that specific type. Think of it as if you had declared your variable using an interface instead. Sure I am working with a Student instance, but I am only working with it as a Person instance or as IPerson.
Normally as a variable in a method you wouldn't do that because pretty much the defacto standard is to just use var for everything nowadays. Where you do make the choice to define Person is normally on properties, method return values, and method parameters. Local variable is not really important.
Because Student class is derived from Person class, any Student object is also a Person object. Thus a notation Person ps = new Student(); means we're declaring variable ps to be of type Person and instantiate it as Student. It could be used if you have a method that takes Person object as parameter, e.g.
public void Foo(Person p) { if(p.Age > 21) Console.WriteLine("OK to drink!"); }
However, if you have a method that operates on properties of derived class you must declare and instantiate the instance of it. So for
public void Foo(Student s) {if(s.YearOfStudy == 1) Console.WriteLine("Freshman"); }
you must use Student s = new Student();.
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 10 years ago.
for example, I'm trying to initialize a new Person
var me = new Person();
but i'm just wondering if it's possible for that initialization to automatically return a seed?
I'm trying to add it to the constructor but I don't know how?
public class Person
{
public Person Person(){ return ...}
}
well, that doesn't really work. Can anyone explain to me why it doesn't work and if there's another way to do this?
I can do object initialization, but I'm just wondering if this is possible??
you can create a static method (factory)
var seededPerson = Person.CreateNew();
public class Person
{
private Person() {}
public static Person CreateNew()
{
return new Person() { Seed = 123; };
}
}
A constructor initializes the current (newly allocated) instance; nothing more. It cannot return anything. It sounds like you just want a factory method:
public class Person
{
public static Person Create(){ return ...}
}
From your comment:
automatically adds value to the variable (in this case "me") and populating the instantiated object.. ie: having Person.Name = "Joe" and etc... without me manually doing object initialization or what not... basically I want the model/class to create its own data right after I instantiate it..
Just add implementation to the parameterless constructor:
public class Person
{
public Person()
{
this.Name = "Joe";
}
public string Name { get; set; }
}
When you call var me = new Person();, then Name will already be populated with "Joe".
More usages of constructors
If you want to be able to customize the name more quickly, then you could add parameters to that constructor, or add a different constructor that takes parameters:
public class Person
{
public Person()
: this("Joe") // Calls the other constructor that takes a name...
{
}
public Person(string name)
{
this.Name = name;
}
public string Name { get; set; }
}
var me = new Person(); // Joe
var you = new Person("You");
In the latest .Net, you can also use default values for these parameters to make your code shorter:
public class Person
{
public Person(string name = "Joe") // Will be "Joe" unless you say otherwise
{
this.Name = name;
}
public string Name { get; set; }
}
var me = new Person(); // Joe
var you = new Person("You");
public class Person
{
protected Person()
{
}
public static Person BuildPerson(out int seed)
{
var person = new Person();
seed = RuntimeHelpers.GetHashCode(person);
return person;
}
}
You mean this? Using a "surrogate" constructor based on a static method?
or
public class Person
{
public Person(out int seed)
{
seed = RuntimeHelpers.GetHashCode(this);
}
}
a constructor with an out argument?
As a sidenote, RuntimeHelpers.GetHashCode(object) returns a pseudo unique id of an object. Pseudo unique because these numbers can be reused by .NET. A better "implementation" that always give unique ids would be:
public class Person
{
private static int seed;
public Person(out int seed)
{
seed = Interlocked.Increment(ref Person.seed);
}
}
using the Interlocked.Increment to make the constructor thread safe.
This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
Is this keyword optional when accessing members in C#?
When do you use the “this” keyword?
class Program
{
public class Demo
{
int age;
string name;
public Demo(int age, string name)
{
// 'THIS' KEYWORD IS ADDED IN THESE TWO LINES THEN ONLY IT WORKS
age = age;
name = name;
}
public void Show()
{
Console.WriteLine("Your age is :" + age.ToString());
Console.WriteLine("Your name is : " + name);
}
}
static void Main(string[] args)
{
int SENDage;
string SENDname;
Console.WriteLine("Enter your age : " );
SENDage=Int32.Parse(Console.ReadLine());
Console.WriteLine("Enter your name : ");
SENDname=Console.ReadLine();
Demo obj = new Demo(SENDage, SENDname);
obj.Show();
Console.ReadLine();
}
}
I found this reason , but can anyone please explain it to me?
Local data members age , name have precedence over instance members.
I am not able to understand it.
In this situation the this keyword would not be required. It is only necessary when the following declaration is changed:
int a;
string n;
Into
int age;
string name;
To use the class variable instead of the argument to the constructor you would then have to assign it with this:
public Demo(int age, string name){
this.age = age;
this.name = name;
}
This code runs just fine for me when I copy-paste it into a console application.
What do you mean by "this" keyword is required? doesn't it compile? what version of Visual Studio are you using?
Alternatively, Is this the whole code or just a demo you made portraying the problem?
From the error message it seems like you have "age" and "name" defined somewhere else, perhaps "a" and "n" were previously called "age" and "name"?
In your code the parameter name age and class member age are of same name.
public class Demo
{
int age;
string name;
public Demo(int age, string name)
{
age = age;
name = name;
}
.....
}
When your code executes the constructor, it first searches for the local variable and then searches for the class variables. Since it gets the age and name both as local variable it reassigns the value back to it self.
Now if you use this keyword for assigning values, this keyword refers to the current object and hence assigns the value to the object.
public class Demo
{
int age;
string name;
public Demo(int age, string name)
{
this.age = age;
this.name = name;
}
.....
}