i am new at c# and i have a problem in this small program
i want to return the entered information in method ClientsDetails to use them in method Print().
Any help plz ?
public static void Main(string[] args)
{
ClientsDetails();
Print(???,???,???);
Console.ReadLine();
}
public static void ClientsDetails()
{
Console.Write("Client's first name: ");
string firstName = Console.ReadLine();
Console.Write("Client's last name: ");
string lastName = Console.ReadLine();
Console.Write("Client's birthdate: ");
string birthday = Console.ReadLine();
}
public static void Print(string first, string last, string birthday)
{
Console.WriteLine("Client : {0} {1} was born on: {2}", first, last, Birthday);
}
}
You could use a struct:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
struct Person{
public static FirstName;
public static LastName;
public static Birthday;
}
class Program
{
static void Main(string[] args)
{
Person person = ClientsDetails();
Print(person.FirstName, person.LastName, person.Birthday);
Console.ReadKey();
}
public static Person ClientsDetails()
{
Person returnValue = new Person();
Console.Write("Client's first name: ");
returnValue.FirstName = Console.ReadLine();
Console.Write("Client's last name: ");
returnValue.LastName = Console.ReadLine();
Console.Write("Client's birthdate: ");
returnValue.Birthday = Console.ReadLine();
return returnValue;
}
public static void Print(string first, string last, string birthday)
{
Console.WriteLine(String.Format("Client : {0} {1} was born on: {2}", first, last, birthday));
}
}
}
Or an array:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string person = ClientsDetails();
Print(person[0], person[1], person[2]);
Console.ReadKey();
}
public static string[] ClientsDetails()
{
string[] returnValue = new string[3];
Console.Write("Client's first name: ");
returnValue[0] = Console.ReadLine();
Console.Write("Client's last name: ");
returnValue[1] = Console.ReadLine();
Console.Write("Client's birthdate: ");
returnValue[3] = Console.ReadLine();
return returnValue;
}
public static void Print(string first, string last, string birthday)
{
Console.WriteLine(String.Format("Client : {0} {1} was born on: {2}", first, last, birthday));
}
}
}
Or references (pass by reference):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string firstName, lastName, birthday;
ClientsDetails(ref firstName, ref lastName, ref birthday);
Print(firstName, lastName, birthday);
Console.ReadKey();
}
public static void ClientsDetails(ref string firstName, ref string lastName, ref string birthday)
{
Console.Write("Client's first name: ");
firstName = Console.ReadLine();
Console.Write("Client's last name: ");
lastName = Console.ReadLine();
Console.Write("Client's birthdate: ");
birthday = Console.ReadLine();
}
public static void Print(string first, string last, string birthday)
{
Console.WriteLine(String.Format("Client : {0} {1} was born on: {2}", first, last, birthday));
}
}
}
I just corrected your program as your requirement.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
private static String FirstName;
private static String LastName;
private static String Birthday;
static void Main(string[] args)
{
ClientsDetails();
Print(FirstName, LastName, Birthday);
Console.ReadKey();
}
public static void ClientsDetails()
{
Console.Write("Client's first name: ");
FirstName = Console.ReadLine();
Console.Write("Client's last name: ");
LastName = Console.ReadLine();
Console.Write("Client's birthdate: ");
Birthday = Console.ReadLine();
}
public static void Print(string first, string last, string birthday)
{
Console.WriteLine(String.Format("Client : {0} {1} was born on: {2}", first, last, Birthday));
}
}
}
There is a heap of way that you can pass the required arguments to your method, so for example simply you can do it like this:
String f = "first string";
String l = "last string";
String b = "birthday string";
Print(f,l,b);
BTW, in your case it seems that you want the user's inputs to be passed to the Print method, so a simple way is to just call the Print method inside your ClientsDetails method like this:
Print(firstName, lastName, birthday);
For a comprehensive resource about this, you can refer to the docs, as always. At the moment you can just neglect the Async Methods part.
Related
What am i doing wrong? I am trying to have my program read the data from a csv file but i keep getting this unhandled exception, is it because of how i wrote the txt file? the exception?
First I tried to have the data be displayed as a list in the console, but that did not happened either. I cant seem to be able to do that here or even get it right to read from my txt file.
//My first program
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PracticeProgram
{
public class Program
{
public static bool W2 { get; private set; }
public static void Main(string[] args)
{
List<Person> myContacts = new List<Person>();
// Loop to collect developers data
for (int i = 0; i < 4; i++)
{
Console.WriteLine("Welcome developer, enter your name to continue");
string name = Console.ReadLine();
Console.WriteLine("Hello, " + name);
Console.WriteLine("enter your address");
string address = Console.ReadLine();
Console.WriteLine(address);
Console.WriteLine("enter your monthly income");
double GrossMonthlyPay = 5000;
Console.WriteLine(GrossMonthlyPay);
Console.ReadLine();
Console.WriteLine("your tax deduction is set at 7%");
double taxes = (0.07);
Console.WriteLine(taxes);
Console.ReadLine();
Console.WriteLine("your monthly tax deduction is ");
Console.WriteLine(taxes = GrossMonthlyPay * taxes);
Console.ReadLine();
Console.WriteLine("Based on your monthly income your Annual gross pay is ");
double AnnualGrossPay = GrossMonthlyPay * 12;
Console.WriteLine(AnnualGrossPay);
Console.ReadLine();
Console.WriteLine("Your annual taxes are ");
double AnnualTaxes = AnnualGrossPay * 0.07;
Console.WriteLine(AnnualTaxes);
Console.ReadLine();
Console.WriteLine("Select 1 for W2, select 2 for 1099");
bool A = W2;
Console.WriteLine();
Console.ReadLine();
if (A)
{
Console.WriteLine("You employment type is W2");
}
else
{
Console.WriteLine("Your employment type is 1099");
}
Console.Write("\nPress any key to continue...");
Console.ReadLine();
myContacts.Add(new Person(name, address, GrossMonthlyPay, taxes, AnnualGrossPay, AnnualTaxes));
}
// Or you could read from CSV or any other source
foreach (string line in System.IO.File.ReadLines(#"C:\Users\Owner\Documents\Visual Studio 2015\Projects\new\data.txt"))
{
myContacts.Add(Person.ReadFromCSV(line));
}
// Serialize your informations at the end
foreach (Person contact in myContacts)
{
contact.SerializeToCSV(#"C:\Users\Owner\Documents\Visual Studio 2015\Projects\new\data.txt");
}
}
}
internal class Person
{
private string address;
private double grossMonthlyPay;
private string name;
private double taxes;
private double annualGrossPay;
private double annualTaxes;
public Person(string name, string address, double grossMonthlyPay, double taxes)
{
this.name = name;
this.address = address;
this.grossMonthlyPay = grossMonthlyPay;
this.taxes = taxes;
}
public Person(string name, string address, double grossMonthlyPay, double taxes, double annualGrossPay, double annualTaxes) : this(name, address, grossMonthlyPay, taxes)
{
this.annualGrossPay = annualGrossPay;
this.annualTaxes = annualTaxes;
}
public override string ToString()
{
return "Name=" + this.name + ",Address =" + this.address + " Monthly Pay=" + this.grossMonthlyPay + " Taxes=" + this.taxes.ToString();
}
internal static Person ReadFromCSV(string line)
{
throw new NotImplementedException();
}
internal void SerializeToCSV(string v)
{
throw new NotImplementedException();
}
}
}
this is the error
Your function "ReadFromCSV" implement a
throw new NotImplementedException();
try to delete it or implement with the right code
i am a begginer in c# .
my problem is that i want to create a list of objects that i can add objects dynamically and then print their properties(i want to go to every object that i want and print only his properties).
i looked around the internet and didn't find a good answer that will help me understand how to to do it correctly.
i added a try...catch to understand the problem but the explantation i got is that i didn't add instance to print his properties even that i totaly did it.
i am really lost so any help would be appreciated.
my code :
class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using APPcLASS_2;
using System.Collections;
namespace EmployeesBooks
{
public class EMpLOYcLaSS
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int PhoneNumber { get; set; }
public string Adress { get; set; }
public int Days { get; set; }
public int Mounths { get; set; }
public int Years { get; set; }
}
}
main program:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using APPcLASS_2;
using EmployeesBooks;
namespace EmployeesBooks
{
class Program
{
static void Main(string[] args)
{
EMpLOYcLaSS Employ = new EMpLOYcLaSS();
List<EMpLOYcLaSS> ListOfObjects = new List<EMpLOYcLaSS>();
string FirstNameVar, LastNameVar, AdressVar;
int PhoneNumberVar, DayVar, MounthVar, YearVar;
while(true)
{
Console.Clear();
Console.WriteLine("Enter your choise:");
Console.WriteLine("1-Add an employee");
Console.WriteLine("2-Earase employee");
Console.WriteLine("3-Show reports");
var choise=int.Parse(Console.ReadLine());
switch(choise)
{
case 1:
Console.WriteLine("Enter First Name:",Employ.FirstName);
FirstNameVar = Console.ReadLine();
Employ.FirstName = FirstNameVar;
Console.WriteLine("Enter Last Name:");
LastNameVar = Console.ReadLine();
Employ.LastName = LastNameVar;
Console.WriteLine("Enter Phone Number:");
PhoneNumberVar =int.Parse(Console.ReadLine());
Employ.PhoneNumber = PhoneNumberVar;
Console.WriteLine("Enter Address:");
AdressVar = Console.ReadLine();
Employ.Adress = AdressVar;
Console.WriteLine("Enter Birthday:");
Console.WriteLine("Day:");
DayVar =int.Parse(Console.ReadLine());
Employ.Days = DayVar;
Console.WriteLine("Mounth:");
MounthVar = int.Parse(Console.ReadLine());
Employ.Mounths = MounthVar;
Console.WriteLine("Year:");
YearVar = int.Parse(Console.ReadLine());
Employ.Years = YearVar;
ListOfObjects.Add(new EMpLOYcLaSS());
break;
case 3:
try
{
Console.WriteLine("enter a number of employee:(1,2,3,4...)");
var EmployeeNumberForPrinting = int.Parse(Console.ReadLine());
if (ListOfObjects[EmployeeNumberForPrinting] != null)
Console.WriteLine("{0}", ListOfObjects[EmployeeNumberForPrinting].FirstName.ToString());
else
Console.WriteLine("Don't Exist!");
Console.WriteLine("Press any key to proceed");
Console.ReadKey();
break;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
break;
}
}
}
}
}
}
Well first of all you don't add the employee into the list, you add a new one.
Change
ListOfObjects.Add(new EMpLOYcLaSS());
To
ListOfObjects.Add(Employ);
That will add the employee you created into the list, now to print each employee's name for example.
foreach(var e in ListOfObjects)
{
Console.WriteLine(e.FirstName + " " + e.LastName);
}
Obviously you can add more properties as you wish, this simply goes through all the objects and prints each of their names. Your code to print a predetermined employee should work now, just remove ToString() as it's already a string. Just a note, remember 0 is the first index in a list. I recommend for usability add one to EmployeeNumberForPrinting due to this, your decision.
Cant't figure out what I am doing wrong,want to display user name in console through a method in the same class,missing a minor syntax please have a look and guide me.
public class Program
{
string name;
public void GetName()
{
Console.WriteLine("Enter ur name");
name = Console.ReadLine();
Console.WriteLine("Name is",name);
Console.ReadLine();
}
static void Main()
{
Program p = new Program();
p.GetName();
Console.ReadLine();
}
}
You need to specify the format string try:
public class Program
{
string name;
public void GetName()
{
Console.WriteLine("Enter ur name");
name = Console.ReadLine();
Console.WriteLine("Name is {0}",name);
Console.ReadLine();
}
static void Main()
{
Program p = new Program();
p.GetName();
Console.ReadLine();
}
}
You can also do it like this
Console.Writeline("name is:" + name);
Console.WriteLine("Name is : " + name);
So I've been looking into this for what feel like forever and can not figure out what I'm doing wrong. here are excerpts from my code where I want the string CashierLOgInNName's value to be the new Cashier objects name:
public class Cashiers
{
public int CashierID;
public int Password;
public string FirstName;
public string LastName;
public void SetCashiers(int CashierID, int Password,string FirstName, string LastName )
{
this.CashierID = CashierID;
this.Password = Password;
this.FirstName=FirstName;
this.LastName = LastName;
}
Console.WriteLine("enter New Log in name");
string CashierLOgInNName= Console.ReadLine();
Console.WriteLine("enter First Name");
string CashierFirstName = Console.ReadLine();
Console.WriteLine("enter Last name");
string CashierLastName = Console.ReadLine();
Console.WriteLine("enter Cashier ID");
string f = Console.ReadLine();
int NewCashierID = Int32.Parse(f);
Console.WriteLine("enter Cashier Password");
string g = Console.ReadLine();
int NewCashierPWD = Int32.Parse(g);
CashierLOgInNName = (Cashiers)Activator.CreateInstance(null, CashierLOgInNName).Unwrap();
First a little correction. It will make sure the Cashier's Object cashierObj is created.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Activators
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("enter New Log in name");
string CashierLOgInNName = Console.ReadLine();
Console.WriteLine("enter First Name");
string CashierFirstName = Console.ReadLine();
Console.WriteLine("enter Last name");
string CashierLastName = Console.ReadLine();
Console.WriteLine("enter Cashier ID");
string f = Console.ReadLine();
int NewCashierID = Int32.Parse(f);
Console.WriteLine("enter Cashier Password");
string g = Console.ReadLine();
Cashiers cashierObj = (Cashiers)Activator.CreateInstance(typeof(Cashiers), f, g, CashierFirstName, CashierLastName);
}
}
public class Cashiers
{
public string CashierID;
public string Password;
public string FirstName;
public string LastName;
public Cashiers(string CashierID, string Password, string FirstName, string LastName)
{
this.CashierID = CashierID;
this.Password = Password;
this.FirstName = FirstName;
this.LastName = LastName;
}
}
}
Coming to the next part CashierLOgInNName's value to be the new Cashier objects name. This seems to be tricky and non useful. I suggest there are better alternatives :
You can define property loginName in Cashiers.
You can create a Dictionary<string, Cashier> LoginName as key and Cashier Object as value.
But still if you persist there is a way using CSharpCodeProvider Class which allows dynamically creating an assembly from source code.
In source code you can write the object name as loginName and then refer that assembly dynamically.
Yet it serves you no purpose as you will not be able to use that object as its name is known to you at run time only. I hope it helps your curiosity.
βIn a time of destruction, create something.β β Maxine Hong Kingston
The MSDN documentation of activator.createinstance and objecthandle.unwrap might be of help.
Activator.CreateInstance Method
ObjectHandle.Unwrap Method
I was just making this program to experiment with lists and such, and I was curious as to why in the foreach loop the Object always shows up as the "Minecraft" Wish object. Is it because it was the last Wish object to be created? And how can I fix it, so all 3 Wish objects which have been declared show up?
Thanks!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Wish iPod = new Wish("iPod", "Various", 299.00);
Wish Phone = new Wish("New Phone", "Various", 00.00);
Wish Minecraft = new Wish("Minecraft Account", "www.minecraft.net", 30.00);
List<Wish> Wishlist = new List<Wish>();
Wishlist.Add(Phone);
Wishlist.Add(iPod);
Wishlist.Add(Minecraft);
Console.WriteLine("Toby's Wishlist");
Console.WriteLine("If cost is 00.00, the Wish's cost varies.");
Console.WriteLine(" ");
foreach (Wish wish in Wishlist)
{
Console.WriteLine("---Wish---");
Console.WriteLine("Name: {0}", wish.getName());
Console.WriteLine("Store: {0}", wish.getStore());
Console.WriteLine("Cost: ${0}", wish.getCost().ToString());
Console.WriteLine("----------");
Console.WriteLine(" ");
}
Console.ReadLine();
}
}
public class Wish
{
static string Name, Store;
static double ApproxCost;
public Wish(string name, string store, double approxCost)
{
Name = name;
Store = store;
ApproxCost = approxCost;
}
public string getName()
{
return Name;
}
public string getStore()
{
return Store;
}
public double getCost()
{
return ApproxCost;
}
}
}
Remove static from Wish members declaration
static means that the data will be shared across all the instances. So static members are also so called class variables. While not static members - are object variables.
It's because in class Wish you declared Name, Score, and ApproxCost as static.