see the below is my code. I have some question regarding that.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace myConsole
{
class Program
{
static void Main(string[] args)
{
Customer cust1 = new Customer(1,"gaurav",27,567.90);
Customer cust2 = new Customer(2, "manav", 28, 533.90);
Customer cust3 = new Customer(3, "anuj", 29, 500.90);
Customer.Do_Work();
}
}
public class Customer
{
private int _id;
private string _name;
private int _age;
private double _amt;
public Customer(int Id, string Name, int Age, double Amt)
{
Id = _id;
Name = _name;
Age = _age;
Amt = _amt;
}
public int ID
{
get { return _id; }
set { _id = value; }
}
public string NAME
{
get { return _name; }
set { _name = value; }
}
public int AGE
{
get { return _age; }
set
{
if (_age > 100)
{
// show msgs
}
else
{
_age = value;
}
}
}
public double AMOUNT
{
get { return _amt; }
set { _amt = value; }
}
public static void Do_Work()
{
Console.WriteLine("Yes I am working");
}
}
}
1. It is the right way to add new customers like
Customer cust..n = new Customer(n1, "nn",23n, 333.44);
2. Do I need to create a construtor like below
public Customer(int Id, string Name, int Age, double Amt)
3. How can I print all the cistomres in console.writeline(?)
4. without useing constructor How could I add customers
Thanks Gaurav
It is our choices that show what we truly are, far more than our abilities...
That's perfectly reasonable. Of course, you might want to store the customers in a collection, such as a list, to make it easier to iterate over them later.
In this case you could do
List<Customer> customers = new List<Customer>();
customers.Add( new Customer( ... ) );
In fact, C# has a syntactic shortcut for creating lists, which you can check in the documentation.
demoninside9
2. Do I need to create a construtor like below
You don't necessarily need a constructor like this. Instead, you could simply create an object then set the properties. However, constructors like this offer both convenience and also the notion of object validity. In other words, you can force someone to
provide the information that you want by requiring them to use a constructor that takes the information.
demoninside9
3. How can I print all the cistomres in console.writeline(?)
If you were to use a list, then you could iterate the list with a foreach() block. Without a list you will need to call Console.WriteLine() once per Customer object explicitly.
demoninside9
4. without useing constructor How could I add customers
Object creation in C# requires a constructor of some description or other.
You don't necessarily need a constructor like this. Instead, you could simply create an object then set the properties. However, constructors like this offer both convenience and also the notion of object validity. In other words, you can force someone to
provide the information that you want by requiring them to use a constructor that takes the information.
could You please write some code regarding this, I meant how should I add customers with out using a constructor.
Thanks
Gaurav
It is our choices that show what we truly are, far more than our abilities...
two ways you can call Default cunstructor without need of explicit constructor, see the code,
Method 1:
List<Customer> customers = new List<Customer>()
{
new Customer()
{
AGE = 1,
NAME = "gaurav",
AMOUNT = 27567.90
},
new Customer()
{AGE = 2,
NAME = "manav",
AMOUNT = 28533.90},
new Customer()
{AGE = 3,
NAME = "anuj",
AMOUNT = 29500.90
}
};
Method 2:
var cust1 = new Customer()
{
AGE = 1,
NAME = "gaurav",
AMOUNT = 27567.90
};
var cust2 = new Customer()
{
AGE = 1,
NAME = "gaurav",
AMOUNT = 27567.90
};
var cust3 = new Customer()
{
AGE = 1,
NAME = "gaurav",
AMOUNT = 27567.90
};
public class Customer
{
private int _id;
private string _name;
private int _age;
private double _amt;
//public Customer(int Id, string Name, int Age, double Amt)
//{
// Id = _id;
// Name = _name;
// Age = _age;
// Amt = _amt;
//}
//public Customer()
//{
//}
public int ID
{
get { return _id; }
set { _id = value; }
}
public string NAME
{
get { return _name; }
set { _name = value; }
}
public int AGE
{
get { return _age; }
set
{
if (_age > 100)
{
// show msgs
}
else
{
_age = value;
}
}
}
public double AMOUNT
{
get { return _amt; }
set { _amt = value; }
}
public static void Do_Work(IEnumerable<Customer> pCustomers)
{
int iCounter = 0;
foreach (var pCustomer in pCustomers)
{
iCounter++;
Console.WriteLine(string.Format("Customer {0} : Name : {1}, Age : {2}, Amount : {3}", iCounter.ToString(), pCustomer.NAME, pCustomer.AGE.ToString(), pCustomer.AMOUNT.ToString()));
Console.ReadLine();
}
}
2- no you dont, but you can create any sort of constructor with any number/combination of the Customer class, if you realise you need it! :)
3- You need to have a structure that hold Customers, ie a List of Customers.
Example:
List<Customer> listCustomers = new List<Customer>();
...then you must add custumers to the list:
listCustomers.Add(cust1);
....
You can always override ToString() in the Customer class
public override string ToString()
{
return "Customer "+NAME; //example!
}
and finally create a foreach loop to write each customer
foreach(Customer cust in listCustomers)
{
Console.WriteLine(cust.ToString());
}
4-I dont think that is possible, a constructor is a data type initializer, so in order to initialize a data object of type Customer, you need to use the Customer contructor!
In general, if constucting an object is simple (like you have shown) then providing appropriate constructors is fine. If construction is even a little more complex (maybe you have to look something up in a database, maybe you need some conditional logic,
maybe you need to call a service) then you would be better off using a factory method. A factory method is a static method in another class (the 'factory') which knows how to make objects. It's signature might be something like
public static Customer MakePreferred(int id, string name, double last12MonthsSpend)
This factory method might use the last12MonthsSpend in some complex logic to determine the appropriate amount of credit available to the customer and return a Customer object with the appropriate values set.
Think about a real world car and how you would model it in software. There would be all sorts of methods to 'Accelerate', 'IndicateTurn', 'ReceiveFuel' and so on. These are all things that real cars do. One thing that a real car does not do is construct
itself. Construction of real cars is a specialised activity which is done in a factory. It makes sense for a Car object in a program to also be constructed in a factory.
The constructor in your original post is wrong. You have assigned internal fields to the parameters (Id = _id) which is back to front. The purpose of the constructor is to build a Customer by using information that has been passed to it. The body of the
constructor should be
this.ID = Id;
(using 'this' is not really required but makes it clear that the left hand side is a property of the instance being constructed)
Also, get rid of a lot of your code. For example the property ID can just be
public int ID {get; set;}
and now you can delete the _id field.
The same optimisation can be done for Name and Amount
By the way, don't yell - NAME and AMOUNT. All uppercase is associated with a different convention.
It's a matter of style but I would have the Age property throw an exception if the value does not meet your requirements (I notice that you allow negative ages but not an age of 100, which is a little odd). The callers who are setting the property should
pass legal values and should deal with any problems that arise themselves. What if Customer is used by a client which does not have a visual interface? The way that your code is written you have to assume a lot about the environment that has called you.
What colours (style in general) should the messgae use? Is the client a console application, WinForms, WPF, Silerlight, WebForms, MVC, a web service or ...? Much better to let the client deal with any problems in a manner which is best for that client.
demoninside9
Participant
1182 Points
1697 Posts
It is the right way to do so: Constructor
Jan 31, 2012 08:22 AM|LINK
hi all
see the below is my code. I have some question regarding that.
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace myConsole { class Program { static void Main(string[] args) { Customer cust1 = new Customer(1,"gaurav",27,567.90); Customer cust2 = new Customer(2, "manav", 28, 533.90); Customer cust3 = new Customer(3, "anuj", 29, 500.90); Customer.Do_Work(); } } public class Customer { private int _id; private string _name; private int _age; private double _amt; public Customer(int Id, string Name, int Age, double Amt) { Id = _id; Name = _name; Age = _age; Amt = _amt; } public int ID { get { return _id; } set { _id = value; } } public string NAME { get { return _name; } set { _name = value; } } public int AGE { get { return _age; } set { if (_age > 100) { // show msgs } else { _age = value; } } } public double AMOUNT { get { return _amt; } set { _amt = value; } } public static void Do_Work() { Console.WriteLine("Yes I am working"); } } }1. It is the right way to add new customers like
DMW
All-Star
15943 Points
2353 Posts
Re: It is the right way to do so: Constructor
Jan 31, 2012 08:41 AM|LINK
That's perfectly reasonable. Of course, you might want to store the customers in a collection, such as a list, to make it easier to iterate over them later.
In this case you could do
List<Customer> customers = new List<Customer>();
customers.Add( new Customer( ... ) );
In fact, C# has a syntactic shortcut for creating lists, which you can check in the documentation.
You don't necessarily need a constructor like this. Instead, you could simply create an object then set the properties. However, constructors like this offer both convenience and also the notion of object validity. In other words, you can force someone to provide the information that you want by requiring them to use a constructor that takes the information.
If you were to use a list, then you could iterate the list with a foreach() block. Without a list you will need to call Console.WriteLine() once per Customer object explicitly.
Object creation in C# requires a constructor of some description or other.
Dave
demoninside9
Participant
1182 Points
1697 Posts
Re: It is the right way to do so: Constructor
Jan 31, 2012 08:43 AM|LINK
could You please write some code regarding this, I meant how should I add customers with out using a constructor.
Thanks
Gaurav
Kishore Bari...
Participant
879 Points
182 Posts
Re: It is the right way to do so: Constructor
Jan 31, 2012 08:45 AM|LINK
Hi,
two ways you can call Default cunstructor without need of explicit constructor, see the code,
Method 1:
List<Customer> customers = new List<Customer>() { new Customer() { AGE = 1, NAME = "gaurav", AMOUNT = 27567.90 }, new Customer() {AGE = 2, NAME = "manav", AMOUNT = 28533.90}, new Customer() {AGE = 3, NAME = "anuj", AMOUNT = 29500.90 } };Method 2:
var cust1 = new Customer() { AGE = 1, NAME = "gaurav", AMOUNT = 27567.90 }; var cust2 = new Customer() { AGE = 1, NAME = "gaurav", AMOUNT = 27567.90 }; var cust3 = new Customer() { AGE = 1, NAME = "gaurav", AMOUNT = 27567.90 };public class Customer { private int _id; private string _name; private int _age; private double _amt; //public Customer(int Id, string Name, int Age, double Amt) //{ // Id = _id; // Name = _name; // Age = _age; // Amt = _amt; //} //public Customer() //{ //} public int ID { get { return _id; } set { _id = value; } } public string NAME { get { return _name; } set { _name = value; } } public int AGE { get { return _age; } set { if (_age > 100) { // show msgs } else { _age = value; } } } public double AMOUNT { get { return _amt; } set { _amt = value; } } public static void Do_Work(IEnumerable<Customer> pCustomers) { int iCounter = 0; foreach (var pCustomer in pCustomers) { iCounter++; Console.WriteLine(string.Format("Customer {0} : Name : {1}, Age : {2}, Amount : {3}", iCounter.ToString(), pCustomer.NAME, pCustomer.AGE.ToString(), pCustomer.AMOUNT.ToString())); Console.ReadLine(); } }Hope this will help you
Insync Tech-Fin Solutions Ltd.
(India)
DMW
All-Star
15943 Points
2353 Posts
Re: It is the right way to do so: Constructor
Jan 31, 2012 08:48 AM|LINK
Go to google.
Type C# constructor in the search.
Read the many links there.
I'm afraid that I can't teach you to program via a forum. There are many good online tutorials and programming guides, which you should study first.
Dave
ze.espogeira
Member
383 Points
101 Posts
Re: It is the right way to do so: Constructor
Jan 31, 2012 08:50 AM|LINK
Hi,
in my opinion,
1- yes
2- no you dont, but you can create any sort of constructor with any number/combination of the Customer class, if you realise you need it! :)
3- You need to have a structure that hold Customers, ie a List of Customers.
Example:
List<Customer> listCustomers = new List<Customer>();
...then you must add custumers to the list:
listCustomers.Add(cust1);
....
You can always override ToString() in the Customer class
public override string ToString()
{
return "Customer "+NAME; //example!
}
and finally create a foreach loop to write each customer
foreach(Customer cust in listCustomers)
{
Console.WriteLine(cust.ToString());
}
4-I dont think that is possible, a constructor is a data type initializer, so in order to initialize a data object of type Customer, you need to use the Customer contructor!
Hope it helps
demoninside9
Participant
1182 Points
1697 Posts
Re: It is the right way to do so: Constructor
Jan 31, 2012 09:04 AM|LINK
I did the same but not showing customers
List<Customer> myList = new List<Customer>(); myList.Add(new Customer(1, "gaurav", 180, 567.90)); myList.Add(new Customer(2, "manav", 28, 533.90)); myList.Add(new Customer(3, "anuj", 29, 500.90)); foreach (Customer pCustomer in myList) { Console.WriteLine(pCustomer.ToString()); }Thanks
Kishore Bari...
Participant
879 Points
182 Posts
Re: It is the right way to do so: Constructor
Jan 31, 2012 12:25 PM|LINK
Hi,
Please check if project type is console aplication or not, might be problem is there.
In windows application, just bind the Datagridview with the list, even you wont need foreach loop.
If you have problem please reply back.
Thanks
Insync Tech-Fin Solutions Ltd.
(India)
fred_b
Member
362 Points
81 Posts
Re: It is the right way to do so: Constructor
Jan 31, 2012 03:21 PM|LINK
you should override the tostring like this
public override string ToString() { return "ID: " + ID + "Name: " + NAME + " Age: " + AGE + " Amount: " + AMOUNT; }Paul Linton
Star
13403 Points
2531 Posts
Re: It is the right way to do so: Constructor
Jan 31, 2012 08:44 PM|LINK
In general, if constucting an object is simple (like you have shown) then providing appropriate constructors is fine. If construction is even a little more complex (maybe you have to look something up in a database, maybe you need some conditional logic, maybe you need to call a service) then you would be better off using a factory method. A factory method is a static method in another class (the 'factory') which knows how to make objects. It's signature might be something like
public static Customer MakePreferred(int id, string name, double last12MonthsSpend)
This factory method might use the last12MonthsSpend in some complex logic to determine the appropriate amount of credit available to the customer and return a Customer object with the appropriate values set.
Think about a real world car and how you would model it in software. There would be all sorts of methods to 'Accelerate', 'IndicateTurn', 'ReceiveFuel' and so on. These are all things that real cars do. One thing that a real car does not do is construct itself. Construction of real cars is a specialised activity which is done in a factory. It makes sense for a Car object in a program to also be constructed in a factory.
Have a look at http://www.udidahan.com/2009/06/29/dont-create-aggregate-roots/ It may be a too advanced for where you are at in learning to program but it may open your eyes to some of the concepts that the best developers think about.
The constructor in your original post is wrong. You have assigned internal fields to the parameters (Id = _id) which is back to front. The purpose of the constructor is to build a Customer by using information that has been passed to it. The body of the constructor should be
this.ID = Id;
(using 'this' is not really required but makes it clear that the left hand side is a property of the instance being constructed)
Also, get rid of a lot of your code. For example the property ID can just be
public int ID {get; set;}
and now you can delete the _id field.
The same optimisation can be done for Name and Amount
By the way, don't yell - NAME and AMOUNT. All uppercase is associated with a different convention.
It's a matter of style but I would have the Age property throw an exception if the value does not meet your requirements (I notice that you allow negative ages but not an age of 100, which is a little odd). The callers who are setting the property should pass legal values and should deal with any problems that arise themselves. What if Customer is used by a client which does not have a visual interface? The way that your code is written you have to assume a lot about the environment that has called you. What colours (style in general) should the messgae use? Is the client a console application, WinForms, WPF, Silerlight, WebForms, MVC, a web service or ...? Much better to let the client deal with any problems in a manner which is best for that client.