Object Initialization directly while creating it (set value) [closed] - c#

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 3 years ago.
Improve this question
I'm following this course here and this is live demo
Please I have few questions to ask you, as I want to confirm that I'm understanding what I'm reading :
1) Why does one set value directly while creating object in below code
Transaction t1 = new Transaction("8877", "6/25/2018");
instead of doing like the below; which doesn't work !!!
Transaction transac1 = new Transaction();
transac1.("1234", "2019/10/03");
2) Is public Transaction() { and public Transaction(string c, string d) overloading concept?
3) Is the below a constructor method, using overloading?
public Transaction()
{
tCode = " ";
tDate = " ";
}
4) Why Transaction class doesn't have properties, eventhough I only see two below fields/variable with private access modifiers. whereas I read in OOP book that you must always use properties not to expose fields from outside.
private string tCode;
private string tDate;
public interface ITransactions
{
// interface members
void showTransaction();
}
public class Transaction : ITransactions
{
private string tCode;
private string date;
public Transaction()
{
tCode = " ";
date = " ";
}
public Transaction(string c, string d)
{
tCode = c;
date = d;
}
public void showTransaction()
{
Console.WriteLine("Transaction ID: {0}", tCode);
Console.WriteLine("Date: {0}", date);
}
}
class Tester
{
static void Main(string[] args)
{
Transaction t1 = new Transaction("8877", "6/25/2018");
Transaction t2 = new Transaction("5656", "7/25/2018");
t1.showTransaction();
t2.showTransaction();
Console.ReadKey();
}
}

1)
[...] which doesn't work !!!
Transaction transac1 = new Transaction();
transac1.("1234", "2019/10/03");
Yes, this simply doesn't work, it is invalid syntax. Either you call the constructor new Transaction(); or new Transaction("8877", "6/25/2018");
2)
Is public Transaction() { and public Transaction(string c, string d) overloading concept?
Yes.
3)
Is the below a constructor method, using overloading?
[...]
There is no such thing as "constructor method". You have constructors and you have methods, but there aren't any "constructor methods".
4)
Why Transaction class doesn't have properties, even though I only see two below fields/variable with private access modifiers.
You don't need to expose all the private fields with public properties. It is not a requirement to have public properties for any private field you have. If you don't want to provide such access to any data in your class you don't need to. In this case you only need showTransaction().

Related

Why and when should I use "this" to access methods from base class during inheritance in c#? [duplicate]

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.

How can I create more instances of same object in 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 5 years ago.
Improve this question
There is a simple code:
class Test
{
public int number;
public void method()
{
Console.WriteLine("Something");
}
}
class Program
{
public static void Main(string[] args)
{
while(true)
{
Test obj=new Test();
obj.number=3;
}
}
}
This program sets the "number" of obj to 3 in every moment. But I would like to create a totally another, unique object with copy of content of the original object in every loop, automatically. If I make an object with same name, it will be overwritten.
Naturally I don't want to use it in an endless loop, it would be meaningless, but it was the easiest way to explain my problem.
You are creating new objects each iteration, but you only keep reference to the last created object.
public static void Main(string[] args)
{
var myOjects = new List<Test>();
int startIndex = 1;
while(true)
{
Test obj=new Test();
obj.number=startIndex;
myObjects.Add(obj);
startIndex = startIndex + 1;
if (startIndex > 5) break;
}
}
Now you can go through all objects in your list:
foreach (var obj in myObjects) obj.method();
There are a couple of ways that you can do this.
My first thought would be to use a factory method (it just returns an instance of a class). It would look something like this.
public Test TestFactory()
{
return new Test() { number = 3 };
}
Or add a constructor to the Test class that takes an instance of Test:
// inside Test class
public Test(Test that)
{
number = that.number;
}

How to add new objects [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 6 years ago.
Improve this question
Today i am trying to add another info into a class but i am unable to add. I have tough of adding another class but i am sure that there is a way to modify the class to add more Info.
The info i want to add is
Mr Chan, 1200, 18 Pioneer Rd and
Mr Lee, 600, Blk 21 #21-21 Yishun Rd
class PersonalInfo
{
private string name;
private float salary;
private string address;
public PersonalInfo(string nameVar, float salaryVar, string addressVar)
{
name = nameVar;
salary = salaryVar;
address = addressVar;
}
public void PrintPersonalInfo(TextBox txtPersonalInfo)
{
txtPersonalInfo.Text += name + Environment.NewLine + salary + Environment.NewLine + address + Environment.NewLine + Environment.NewLine;
}
}
That is my code for the class Personal info.
private void btnRun_Click(object sender, EventArgs e)
{
PersonalInfo obj = new PersonalInfo("Mr Tan", 3000, "Blk 123, #12-003 Kepple Rd");
obj.PrintPersonalInfo(txtPersonalinfo);
That is my code for the form.cs So far i can only think of adding new class to add more Info. Now i would like to know how to modify PersonalInfo.cs to add more Info.
Thanks for all you help and have a nice day ahead :)
Perhaps you could consider encapsulating your common properties into a new object, say BasicInfo:
public class BasicInfo
{
public string Name {get; set;}
public float Salary {get; set;}
public string Address {get; set;}
// add more properties when necessary
// e.g. Gender
// public string Gender {get; set;}
}
With that, in the constructor of PersonalInfo class, you can just pass in a BasicInfo object so you don't have to worry about all those properties in the PersonalInfo constructor.
public class PersonalInfo
{
BasicInfo basicInfo;
public PersonalInfo(BasicInfo basicInfo)
{
this.basicInfo = basicInfo;
}
}
You can then keep adding new properties into your BasicInfo class without needing to change PersonalInfo constructor. Hopefully it helps and that's what you are looking for.

Can't access data through multiple class layers [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 8 years ago.
Improve this question
For my Project I have to build a data structure to represent an xml file.
My Idea was to use multiple classes representing the different xml layers.
My problem now is how can I change data in the lowest layer from the uppermost one.
In my code example are three calls 2 work 1 doesn't. Why doesn't the last one work?
Is there another way of organizing the data?
public class option
{
public string optionID;
public void setoptionID(string text)
{
optionID = text;
}
}
public class module
{
public option[] opt = new option[1];
private string moduleID;
public void setmoduleID(string text)
{
moduleID = text;
}
}
public class catalogitem
{
public module[] modul = new module[1];
private string ShortName;
public void setShortName(string text)
{
ShortName = text;
}
}
public class Katalog
{
private catalogitem[] items = new catalogitem[1];
public Katalog()
{
}
public void setcatalogitems()
{
items[0].setShortName("asdf"); //works
catalogitem.modul[0].setmoduleID("5"); //works
items[0].modul[0].setmoduleID("5"); //doesn't work
}
}
For me, none of the three statement work.
You have to initialize the objects itself, not only the array.
items[0] = new catalogitem();
items[0].setShortName("asdf");
items[0].modul[0] = new module();
items[0].modul[0].setmoduleID("5");
But I would also suggest you, to use properties instead of setShortName() / setmoduleID() in your classes and methods for adding and initializing sub items.
Of course it depends on the specification / your intention (that I don't know), but here is a possible way to implement for example
CatalogItem. You can read/write ShortName and enumerate all existing modules. I would take a list, not an array. Modules can be
only added one by one and you can check them before really adding them:
public class CatalogItem
{
private readonly List<Module> mModuls;
public IEnumerable<Module> Moduls
{
get { return mModuls; }
}
public string ShortName { get; set; }
public CatalogItem()
{
mModuls = new List<Module>();
}
public void AddModule(Module module)
{
// Add a check that module is assigned.
mModuls.Add(module);
}
}
Some suggestions
Use properties instead of Set Methods
Write only properties are not good by design
if you need only one object of a type, create the object instead of array with 1 object
follow naming conventions C# Coding Conventions and Naming Guidelines
Your somewhat updated code is below.
public class Option
{
public string OptionID { get; set;}
}
public class Module
{
// if you need only one Option, why not create one public Option object, instead of an Array
public Option Option = new Option();
public string ModuleID { get; set; }
}
public class CatalogItem
{
public Module Module = new Module();
public string ShortName { get; set; }
}
public class Katalog
{
private List<CatalogItem> items = new List<CatalogItem>();
public Katalog()
{
for(int i = 0; i < 10; i++)
items.Add(new CatalogItem());
}
public void SetCatalogItem()
{
foreach(CatalogItem ci in items)
{
ci.ShortName = "asdf";
ci.Module.ModuleID = "5";
}
}
}
Glad to help! Please remember to accept the answer if you found it helpful.

array of pointers to objects in another class [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 8 years ago.
Improve this question
I have to create class like DataBase that will contain menu, adding users, editing them, deleting etc.
Users are from class User.
It looks like:
class base
{
protected int mAccounts=0;
protected const int mMaxAccs=10;
osoba[] list = new osoba[mMaxAccs];
public void menu(){...}
public void add()
{
user user1("Jurand","ze Spychowa",15231512,"1410-10-26","hue#x.com");
mAccounts++;
}
... useless code there
}
then there is User class
class user
{
private string mName;
private string mSurname;
private int mPesel;
private DateTime mBDate;
private string mEmail;
osoba(string mName2, string mSurname2, string mPesel2, string mBDate2, string mEmail2)
{
mName = mName2;
mSurname = mSurname2;
mPesel = Convert.ToInt32(mPesel2);
mBDate = Convert.ToDateTime(mBDate2);
mEmail = mEmail2;
}
The problem is adding new accounts. I totally don't know how to make it working
So the users will be stored in base class and you will have access to edit and add them etc.
Anyone know how to make it working (Creating objects properly)?
I suggest adding properties to User class:
class User
{
public string mName { get; private set; }
public string mSurname { get; private set; }
public int mPesel { get; private set; }
public DateTime mBDate { get; private set; }
public string mEmail { get; private set; }
//constructor for User class
public User(string mName2, string mSurname2, string mPesel2, string mBDate2, string mEmail2)
{
mName = mName2;
mSurname = mSurname2;
mPesel = Convert.ToInt32(mPesel2);
mBDate = Convert.ToDateTime(mBDate2);
mEmail = mEmail2;
}
}
and modify your add method (also changed object where you store data from array to List):
class MyDB
{
List<User> list = new List<User>();
public void add()
{
//use constructor to create new object
User person = new User("Jurand", "ze Spychowa","15231512","1410-10-26","hue#dupa.com");
//add object to list
list.Add(person);
}
}
Its not good idea to mix different languages in code so try avoiding naming objects/methods like "osoba".
You will probably benefit from reading following articles (in Polish):
C# Constructors
C# Properties
I belive that only thing that is missing in your add() method is:
osoba[mAccounts] = user1;
before mAccounts++ line.
Make fields public only if your User class is going to be stupid data object which only store data and contain no methods (maybe except formatting, converting etc.).

Categories