How to call a switch class in main? - c#

I'm a beginner in programming, I have to make a project to university. Can you tell me, how can I call a class with a switch that I've created in main?
I have a switch in main, and after choosing one of options I want it to display next switch.
Switch class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputerServiceTSz
{
class Priceofservices
{
void SuperSwitch()
{
{
int x = 0;
Console.WriteLine("Please, choose type of service.");
Console.WriteLine("1 - Cleaning");
Console.WriteLine("2 - Repair");
Console.WriteLine("3 - Upgrade");
x = int.Parse(Console.ReadLine());
switch (x)
{
case 1:
{
}
break;
case 2:
{
}
break;
}
}
}
}
}
Main class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ComputerServiceTSz
{
class Program
{
static void Main(string[] args)
{
bool done = false;
while(!done)
{
{
int x = 0;
Console.WriteLine("Welcome to computer repair automatic helpdesk.");
Console.WriteLine("1 - List of currently avaivable servisants");
Console.WriteLine("2 - List of services");
Console.WriteLine("3 - Price of services");
Console.WriteLine("4 - Quit");
Console.WriteLine("<------------------------------------------------------>");
x = int.Parse(Console.ReadLine());
switch (x)
{
case 1:
{
List<Servicemanlist> lista = Servicemanlist.CreateServicemanlist();
foreach (var item in lista)
{
Console.WriteLine(item);
}
Console.ReadKey();
}
break;
case 2:
{
List<string> lista = Serviceslist.CreateServicelist();
foreach (var item in lista)
{
Console.WriteLine(item);
}
Console.ReadKey();
}
break;
case 3:
case 4:
{
Console.WriteLine("Bye, see you next time!");
done = true;
Console.ReadKey();
break;
}
}
}
}
}
}
}
I would appreciate some help.

You should create an object of Priceofservices type and call its method SuperSwitch
Priceofservices pos = new Priceofservices();
pos.SuperSwitch();
or you can make SuperSwitch as static and call it without creation.
Priceofservices.SuperSwitch();
Also add public keyword to SuperSwitch to allow access outside the class Priceofservices

Related

How to fix looping issue, even though no loop implemented?

Ok, so I am trying to figure out why I am having a looping issue. The intention of the method GetNewDvdInfo() is to return a new dvd class with 5 properties and will be passed on to DvdController.cs in the CreateDvd() method and will then display all the dvds and the dvd the user added. The problem is that the GetNewDvdInfo() method is repeating itself, but when I was returning null instead, it was not looping.
DvdView.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DvdManager.Models;
/*
GetMenuChoice() : int
GetNewDvdInfo(): Dvd
DisplayDvd(Dvd dvd) : void
EditDvdInfo(Dvd dvd) : Dvd
SearchDvd() : int
ConfirmRemoveDvd(Dvd) : boolean
*/
namespace DvdManager.View
{
public class DvdView
{
public int GetMenuChoice()
{
string input;
int choice;
Console.Clear();
Console.WriteLine("Press 1 to display movies");
Console.WriteLine("Press 2 to add movie");
input = Console.ReadLine();
if (int.TryParse(input, out choice))
{
switch (choice)
{
case 1:
break;
case 2:
break;
default:
Console.WriteLine("Invalid input");
break;
}
}
return choice;
}
public Dvd GetNewDvdInfo() //looping here
{
string inputReleaseYear;
string inputRating;
int id = 4;
string readTitle;
int readReleaseYear;
string readDirector;
float readRating;
Console.WriteLine("What is the Title of the DVD?");
readTitle = Console.ReadLine();
Console.WriteLine("What is the Release Year of the DVD?");
inputReleaseYear = Console.ReadLine();
int.TryParse(inputReleaseYear, out readReleaseYear);
Console.WriteLine("Who is the Director of the DVD?");
readDirector = Console.ReadLine();
Console.WriteLine("What is the star rating of the DVD?");
inputRating = Console.ReadLine();
float.TryParse(inputRating, out readRating);
var dvd = new Dvd(id, readTitle, readReleaseYear, readDirector, readRating);
Dvd newDvd = GetNewDvdInfo();
return dvd;
}
public void DisplayDvd(Dvd dvd)
{
}
public Dvd EditDvdInfo(Dvd dvd)
{
return null;
}
public int SearchDvd()
{
return 0;
}
public Boolean ConfirmRemoveDvd(Dvd dvd)
{
return false;
}
}
}
DvdController.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DvdManager.Models;
using DvdManager.Data;
using DvdManager.View;
/*
Run() : void
Private CreateDvd(): void
Private DisplayDvds(): void
Private SearchDvds(): void
Private EditDvd() : void
Private RemoveDvd() : void
*/
namespace DvdManager.Controllers
{
public class DvdController
{
public DVDList _dvds = new DVDList();
public void Run()
{
Console.WriteLine("Welcome To Dvd Manager");
DvdView view = new DvdView();
var pass = view.GetMenuChoice();
if (pass == 1)
{
CreateDvd();
}
else if (pass == 2)
{
view.GetNewDvdInfo();
CreateDvd();
}
else
Console.WriteLine("Invalid.");
}
private void CreateDvd() //Create
{
var myView = new DvdView();
var dvdInfos = myView.GetNewDvdInfo();
List<Dvd> Dvds = _dvds.GetList();
Dvds.Add(new Dvd(0, "Batman", 2010, "Bruce", 4));
Dvds.Add(new Dvd(1, "Superman", 2009, "John", 4));
Dvds.Add(new Dvd(2, "Wonderwoman", 2012, "Omar", 4));
Dvds.Add(dvdInfos);
DisplayDvds();
}
private void DisplayDvds() //Read List<Dvd> dvds
{
List<Dvd> Dvds = _dvds.GetList();
for (int i = 0; i < Dvds.Count; i++)
{
Console.WriteLine(Dvds[i]);
}
RemoveDvd();
}
private void SearchDvds() //List
{
}
private void EditDvd(int id, Dvd dvd) //Update
{
}
private void RemoveDvd() //Delete int id
{
List<Dvd> Dvds = _dvds.GetList();
//Dvds.RemoveAt(Dvds[1]);
Dvds.Remove(Dvds.Single(x => x.Id == 1));
Console.WriteLine("Removed movie from list:");
for (int i = 0; i < Dvds.Count; i++)
{
Console.WriteLine(Dvds[i]);
}
}
}
}
You are making a recursive call at the end of GetNewDvdInfo(), just remove it.
You are calling this method recursively here:
var dvd = new Dvd(id, readTitle, readReleaseYear, readDirector, readRating);
Dvd newDvd = GetNewDvdInfo(); //!!!
return dvd;
Hence the looping. It seems like this line of code is not needed.

Invoking A Method From Another File C#

I'm having trouble calling my methods. I have 2 separate files. When the user types S then the shake method in my other file will be invoked. So then when the user gets the answer it will be random.
I confused about how to bring that method in another file. Below are both files.
Program.cs:
static void Main(string[] args)
{
Console.WriteLine("Main program!");
Console.WriteLine("Welcome to the Magic 8 Ball");
Console.WriteLine("What would you like to do?");
Console.WriteLine("(S)hake the Ball");
Console.WriteLine("(A)sk a Question");
Console.WriteLine("(G)et the Answer");
Console.WriteLine("(E)xit the Game");
Magic8Ball_Logic.Magic8Ball ball = new Magic8Ball_Logic.Magic8Ball();
string input = Console.ReadLine().ToUpper();
public static string userAnswer = "";
do
{
if (input == "S")
{
if (userAnswer != null)
{
Console.WriteLine("Searching the Mystic Realms(RAM) for the answer");
}
else
{
//Call Method Shake()
}
}
else if (input == "A") {
userAnswer = Console.ReadLine();
}
else if (input == "G") {
//Call Method GetAnswer()
}
} while (input != "E");
}
Magic8Ball.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Magic8Ball_Logic
{
public class Magic8Ball
{
private List<string> _answers;
private int _currentIndex;
private string randomString;
public Magic8Ball()
{
_answers = new List<string>();
_answers.Add("It is certain.");
_answers.Add("It is decidedly so.");
_answers.Add("Without a doubt.");
}
public Magic8Ball(List<string> answers)
{
//I won't use the 20 default. use the ones passed in .
_answers = answers;
}
public void Shake()
{
//picking the index of the answer to show the user
Random r = new Random();
int index = r.Next(_answers.Count);
randomString = _answers[index];
}
public string GetAnswer()
{
//using the index picked by shake to return the answer
//return "";
return randomString;
}
public int AnswerCount
{
get { return _answers.Count; }
}
/* public override string ToString()
{
foreach (var el in _answers)
{
return el;
}
}*/
}
}
First of all you must create an object of this class,then invoke the method.
**Edit**
ball.Shake();
As it was written here: https://stackoverflow.com/a/55986849/10128127
Your Program.cs should be updated like:
replace this comment
//Call Method Shake() with
ball.Shake();
replace this comment
//Call Method GetAnswer() with
ball.GetAnswer();

how to have a comma after each string but not in front

I have a problem with my class where it displays a comma before it displays the string and I cant find a way to take the comma out in the front and keep it in all the other places
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Carnival
{
class Player
{
public string Name { get; set; }
public double SpendingMoney { get; set; }
public string PrizesWon { get; set; }
//constructors
public Player( string n, double sp)
{
Name = n;
SpendingMoney = sp;
PrizesWon = "";
}
//methods
public string Play(GameBooth aGames)
{
string newPrize;
if (SpendingMoney >= aGames.Cost)
{
newPrize = aGames.Start();
//here is what I need to fix
PrizesWon = "," + newPrize + PrizesWon ;
return newPrize;
}
else
{
return "error no money fool";
}
}
}
}
here is the main code if you need it
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Carnival
{
class Program
{
static void Main(string[] args)
{
//local variables
string name;
double money;
int choice = 0;
string newPrize;
//Game objects.
GameBooth balloonDartToss = new GameBooth(2, "tiger plush", "sticker");
GameBooth ringToss = new GameBooth(2, "bear keychain", "pencil");
GameBooth breakAPlate = new GameBooth(1.5, "pig plush", "plastic dinosaur");
Console.ForegroundColor = ConsoleColor.Cyan;
//asking player name
Console.Write("Welcome to the Carnival. What is your name? ");
name = Console.ReadLine();
//asking how much spending money the player has
Console.Write("How much money do you have? ");
money = Convert.ToDouble(Console.ReadLine());
Console.ResetColor();
//Creating player object.
Player Gambler = new Player(name, money);
//main program loop
while (choice != 4)
{
//print menu. Check out the local method below
printMenu();
//retrieve user choice. See the local method below
choice = getChoice();
//main switch. User Choices:
// 1 - we play Baloon Darts Toss and show prize
// 2 - we play ring Toss and show prize
// 3 - we play Break a Plate and show prize
// 4 - Show users all his prizes
switch (choice)
{
case 1:
newPrize = Gambler.Play(balloonDartToss);
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine(newPrize);
break;
case 2:
newPrize = Gambler.Play(ringToss);
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine(newPrize);
break;
case 3:
newPrize = Gambler.Play(breakAPlate);
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine(newPrize);
break;
case 4:
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("{0}, here is your prize list: {1}", Gambler.Name, Gambler.PrizesWon);
Console.ResetColor();
break;
}//end switch
}//end while
//next line simply pauses the program until you hit Enter.
Console.ReadLine();
}//end main
//this method prints the main menu
public static void printMenu()
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine();
Console.WriteLine("Select the game you would like to play:");
Console.WriteLine("1. Balloon Dart Toss");
Console.WriteLine("2. Ring Toss");
Console.WriteLine("3. Break a Plate");
Console.WriteLine("4. Get Prizes and Leave Carnival");
Console.Write("Enter Your Choice: ");
Console.ResetColor();
}//end printMenu
//this methods accepts user input 1-4
public static int getChoice()
{
Console.ForegroundColor = ConsoleColor.Yellow;
int input = 0;
do
{
Console.ForegroundColor = ConsoleColor.Yellow;
input = Convert.ToInt32(Console.ReadLine());
if (input < 1 || input > 4)
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("Out of range. Input 1-4 only");
Console.Write("Enter your choice: ");
Console.ResetColor();
}
} while (input < 1 || input > 4);
Console.ResetColor();
return input;
}
}
}
here is my other class if you need that too but you probably don't
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Carnival
{
class GameBooth
{
//properties
public double Cost { get; set; }
public string FirstPrize { get; set; }
public string ConsolationPrize { get; set; }
public int w { get; set; }
public int l { get; set; }
//constructors
public GameBooth(double c, string fp, string cp)
{
Cost = c;
FirstPrize = fp;
ConsolationPrize = cp;
}
//methods
public string Start()
{
Random r = new Random();
w = 1;
l = 1;
for (int i = 1; i < 3; i++)
{
int randomChoice = r.Next(0, 400);
if ( randomChoice == 1)
{
w++;
}
}
if (w == 3)
{
return FirstPrize;
}
else
{
return ConsolationPrize;
}
}
}
}
Update the line to:
PrizesWon = string.IsNullOrEmpty(PrizesWon) ? newPrize : newPrize + "," + PrizesWon;
This uses the conditional operator to return a different result depending on whether or not PrizesWon already has something in it.
In your code you had put (,) before newPrize. For solving this, you have to just put it after PrizesWon variable and it will look like this :
**PrizesWon = newPrize + PrizesWon + ",";**
I hope your problem will be solved by this.

how to print properties of object in list?

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.

SymbolFinder.FindReferencesAsync doesn't find anything

I want to find all PropertyChangedEventHandler events in my solution, and then find all listeners added to those events. But I can't seem to get a list of the events.
This is all the code in the solution being analyzed:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RoslynTarget
{
public class Example : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged = delegate { };
public void DoNothing() { }
}
}
And this is my code for analyzing it. references.Count == 1 and r.Locations.Count == 0, but exactly one location should be found. What's going on here?
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.MSBuild;
namespace RoslynTest
{
class Program
{
static void Main(string[] args)
{
const string solutionPath = #"C:\Users\<user>\Code\RoslynTarget\RoslynTarget.sln";
const string projectName = "RoslynTarget";
var msWorkspace = MSBuildWorkspace.Create(new Dictionary<string, string> { { "CheckForSystemRuntimeDependency", "true" } });
var solution = msWorkspace.OpenSolutionAsync(solutionPath).Result;
var project =
solution.Projects
.Where(proj => proj.Name == projectName)
.First();
var compilation = project.GetCompilationAsync().Result;
var eventType = compilation.ResolveType("System.ComponentModel.PropertyChangedEventHandler").First();
var references = SymbolFinder.FindReferencesAsync(eventType, solution).Result;
foreach (var r in references)
{
foreach (var loc in r.Locations)
{
// ...
}
}
}
}
}
Extensions.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
namespace RoslynTest
{
public static class Extensions
{
public static IEnumerable<INamedTypeSymbol> ResolveType(this Compilation compilation, string classFullName)
{
return new IAssemblySymbol[] { compilation.Assembly }
.Concat(compilation.References
.Select(compilation.GetAssemblyOrModuleSymbol)
.OfType<IAssemblySymbol>())
.Select(asm => asm.GetTypeByMetadataName(classFullName))
.Where(cls => cls != null);
}
}
}
Recently I've done similar thing where I was trying to find the reference of a method in complete solution.
To use FindReferenceAsync you have create symantic model first and find the symbol from there. Once you have the symbol you can use the FindReferenceAsync.
Here's the snippet that I used and it's working:
var solution = msWorkspace.OpenSolutionAsync(solutionPath).Result;
foreach (var project in solution.Projects)
{
foreach (var document in project.Documents)
{
var model = document.GetSemanticModelAsync().Result;
var methodInvocation = document.GetSyntaxRootAsync().Result;
InvocationExpressionSyntax node = null;
try
{
node = methodInvocation.DescendantNodes().OfType<InvocationExpressionSyntax>()
.Where(x => ((MemberAccessExpressionSyntax)x.Expression).Name.ToString() == methodName).FirstOrDefault();
if (node == null)
continue;
}
catch(Exception exception)
{
// Swallow the exception of type cast.
// Could be avoided by a better filtering on above linq.
continue;
}
methodSymbol = model.GetSymbolInfo(node).Symbol;
found = true;
break;
}
if (found) break;
}
foreach (var item in SymbolFinder.FindReferencesAsync(methodSymbol, solution).Result)
{
foreach (var location in item.Locations)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Project Assembly -> {0}", location.Document.Project.AssemblyName);
Console.ResetColor();
}
}
Here's the complete working code. If you want to visualize the Roslyn tree then you can try using Roslyn tree visualizer to see code structuring.
Update
As per discussion in comments with OP Installing Roslyn SDK fixed the issue. Assuming that there might be some updates in SDK to generate Symbols information as compared to Nuget dlls when using GetCompilationAsync.

Categories