Can you use an array for a Switch(case)? - c#

I've started a Uni course and I can't get me head around how to use my array for a switch case. Basically I just need the help with the switch-case, then I can get on with my work.
Heres what it looks like so far:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
namespace Assignment2
{
class Program
{
public const int noOfentries = 6;
public const int address = 5;
public static string[,] addressBook = new string[noOfentries, address];//
string array for the address book
public static int deletion;
public static int choice;
public static ConsoleKeyInfo keyPressed;
public static short curItem = 0, c;
public static string[,] menuItems = new string[,]
{
{"Add Entry"},
{"Delete Entry"},
{"Print Book to Screen"},
{"Edit Contact"},
{"Exit"}
};
#region addEntry
#endregion
#region deleteEntry
#endregion
#region seeBook
#endregion
public static void fourthChoice()
{
Console.WriteLine("Would you like to edit the name or address?");
}
public static void menu()
{
for (int i = 0; i < 5; i++)
{
Console.WriteLine(menuItems[i,0].PadRight(10));
Console.Clear();
for (c = 0; c < menuItems.Length; c++)
{
if (curItem == c)
{
Console.Write(">");
Console.WriteLine(menuItems[c,0]);
Console.ForegroundColor = ConsoleColor.Green;
}
else
{
Console.WriteLine(menuItems[c,0]);
}
}
Console.WriteLine("Please select an option with the Arrow Keys");
}
}
public static void entries()
{
switch (menuItems[0,0])
{
case "Add Entry":
break;
case "Delete Entry":
break;
case "Print Book to Screen":
break;
case "Edit Contact":
break;
case "Exit":
break;
}
}

There are two aspects to a switch/case:
The value you're switching on
The cases you want to branch to
The fact that you're getting the value from an array is irrelevant. It's equivalent to:
string value = menuItems[0, 0];
switch (value)
{
}
Your cases are also constant string values, so that's fine too. (There's duplication there leading to fragile code which you may want to address, but that's a separate matter.)
... and that's fine. It's not really clear what problem you're having at the moment, although it's also unclear why you've got a rectangular array at all, given that you've only got a single "column" per row. Why not just:
public static string[] menuItems = new string[]
{
"Add Entry",
"Delete Entry",
"Print Book to Screen",
"Edit Contact",
"Exit"
};
(Leaving aside naming, accessibility, mutability etc.)

You should use an Enum for that:
private Enum myEnum { Add, Delete, Edit }
void main(myEnum state)
{
switch (state)
{
Add: //do things
break;
Edit: //do things
break;
Delete: //do things
break;
}
}

Related

My C# code on Visual Studio 2013 doesn't work properly

I am trying to be an educated lazy chemistry student, by making a C# program that can do chemistry calculation for me. In order to make the code, I have to understand well the procedures in chemistry class.
I am new to any kind of programming, C# is my first language.
The code works fine for 1 Element calculation, but not 2 Elements calculation.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication8
{
class Program
{
static void Main(string[] args)
{
MassCalculation myMassCalculation = new MassCalculation();
TwoMassCalculation myTwoMassCalculation = new TwoMassCalculation();
Console.WriteLine("How many elements are in the compound?");
string userMainInput = Console.ReadLine();
if (userMainInput == "1")
{
myMassCalculation.Amount1 = 1;
Console.WriteLine("What is the ELEMENT?");
string userInput1 = Console.ReadLine();
Elements element;
if (Enum.TryParse<Elements>(userInput1, true, out element))
{
switch (element)
{
case Elements.Na:
myMassCalculation.Element1 = 22.990;
break;
case Elements.Cl:
myMassCalculation.Element1 = 35.453;
break;
default:
break;
}
}
Console.WriteLine("How many?");
string userAmount1 = Console.ReadLine();
int myAmount1 = int.Parse(userAmount1);
myMassCalculation.Amount1 = myAmount1;
myMassCalculation.DoCalculation();
resultOfMassCalculation(myMassCalculation);
}
if (userMainInput == "2")
{
Console.WriteLine("What is the First ELEMENT?");
string userInput1 = Console.ReadLine();
Elements element;
if (Enum.TryParse<Elements>(userInput1, true, out element))
{
switch (element)
{
case Elements.Na:
myMassCalculation.Element1 = 22.990;
break;
case Elements.Cl:
myMassCalculation.Element1 = 35.453;
break;
default:
break;
}
}
Console.WriteLine("How many?");
string userAmount1 = Console.ReadLine();
int myAmount1 = int.Parse(userAmount1);
myMassCalculation.Amount1 = myAmount1;
Console.WriteLine("What is the Second ELEMENT?");
string userInput2 = Console.ReadLine();
if (Enum.TryParse<Elements>(userInput2, true, out element))
{
switch (element)
{
case Elements.Na:
myTwoMassCalculation.Element2 = 22.990;
break;
case Elements.Cl:
myTwoMassCalculation.Element2 = 35.453;
break;
default:
break;
}
}
Console.WriteLine("How many?");
string userAmount2 = Console.ReadLine();
int myAmount2 = int.Parse(userAmount2);
myTwoMassCalculation.Amount2 = myAmount2;
myTwoMassCalculation.DoCalculation();
resultOfMassCalculation(myTwoMassCalculation);
}
Console.ReadLine();
}
private static void resultOfMassCalculation(MassCalculation calculation)
{
Console.Write("The Mass is {0}g/mol", calculation.DoCalculation());
}
}
enum Elements
{
Na,
Cl,
}
class MassCalculation
{
public double Element1 { get; set; }
public int Amount1 { get; set; }
public virtual double DoCalculation()
{
double result = Element1 * Amount1;
return result;
}
}
class TwoMassCalculation : MassCalculation
{
public double Element2 { get; set; }
public int Amount2 { get; set; }
public override double DoCalculation()
{
double result = Element1 * Amount1 + Element2 * Amount2;
return result;
}
}
}
Please help! I know it seems somewhat unprofessional. I have just started programming a week ago, and this is the best I can do. I need guidance.
The only elements defined in the code is Na and Cl, I am trying to calculate NaCl. When everything is in place, I will add more elements to the list, and many more different types of calculations.
I'll take constructive opinions.
Thank you so much in advance.
I refactored your code a little. It will work the same way, but wont crash on inappropriate user input
https://dotnetfiddle.net/CMQugr
using System;
using System.Collections.Generic;
namespace Test
{
public class Program
{
public static Dictionary<string, double> Elements = new Dictionary<string, double>
{
{"Na",22.990},
{"Cl",35.453}
};
public static void Main()
{
double result = 0;
int elemenCountInput;
do
{
Console.WriteLine("How many elements are in the compound?");
} while (!Int32.TryParse(Console.ReadLine(), out elemenCountInput));
for (int i = 0; i < elemenCountInput; i++)
{
string element;
do
{
Console.WriteLine("What is the {0} element", (i + 1));
element = Console.ReadLine();
} while (!Elements.ContainsKey(element));
int amount;
do
{
Console.WriteLine("How many");
} while (!Int32.TryParse(Console.ReadLine(), out amount));
result += Elements[element] * amount;
}
Console.Write("The Mass is {0}g/mol", result);
Console.ReadLine();
}
}
}
There is problem in the code when elements are two. You are assigning the first element value to "myMassCalculation' object and second element value to "myTwoMassCalculation". When you call "DoCalculation()" "myTwoMassCalculation.Element1' and "myTwoMassCalculation.Amount1" have no values. That's why it is giving wrong answer. Make the following changes and try:
if (Enum.TryParse<Elements>(userInput1, true, out element))
{
switch (element)
{
case Elements.Na:
myTwoMassCalculation.Element1 = 22.990;
break;
case Elements.Cl:
myTwoMassCalculation.Element1 = 35.453;
break;
default:
break;
}
}
Console.WriteLine("How many?");
string userAmount1 = Console.ReadLine();
int myAmount1 = int.Parse(userAmount1);
myTwoMassCalculation.Amount1 = myAmount1;
I'd do something like:
Create a class for elements (name (string), whatever that number is (double/decimal)
Create a static dictionary of them of them indexed by name.
Loop through the parameters to Main (or loop around an input command) looking up each entry in the dictionary then perform the calculation.
Convert to LINQ if desired.
This is be a great approach and should teach you a lot. I'm not going to write it for you (time and desire), but I may come back later with an example.

C# Constructors and Contexes

I am trying to create a console application that converts centimeters to meters
Here are my objectives
Store number of centimeters entered in an attribute
Use a default constructor to store zero in the attribute that stores the number of centimeters meters entered
Use a primary constructor to accept and store number of centimeters entered.
A function call getMeters to return the number of meters
A function called Remainder to get the number of centimeter remanding after conversion
A function called Printout that will display the results
The application should carry on accepting values for conversion until the user decides to end it.
What I have so far:
using System;
namespace Conv
{
public class Centimeter
{
public int cmvar;
public Centimeter()
{
cmvar = 0;
}
}
//primary const to be added
public class MeterToCenti
{
public static void Main()
{
char choice;
char n = 'n';
do
{
Console.WriteLine("Do you want to continue? (y/n)");
//choice = Console.ReadLine();
choice = Console.ReadKey().KeyChar;
Centimeter c = new Centimeter();
Console.WriteLine("enter value in centimeters");
c.cmvar = int.Parse(Console.ReadLine());
Printout();
}
while(choice.CompareTo(n) == 0);
}
public static void getMeterst()
{
int meters = c.cmvar / 100;
}
public static void Remainder ()
{
int cmremain = c.cmvar % 100;
}
public static void Printout()
{
Console.WriteLine("{0} Meters and {1} Centimeters", meters, cmremain);
}
}
}
I am getting errors regarding:
prog.cs(24,5): warning CS0168: The variable `meters' is declared but never used
prog.cs(41,11): error CS0103: The name `c' does not exist in the current context
prog.cs(41,2): error CS0103: The name `meters' does not exist in the current context
prog.cs(47,24): error CS0103: The name `c' does not exist in the current context
prog.cs(53,61): error CS0103: The name `meters' does not exist in the current context
prog.cs(53,69): error CS0103: The name `cmremain' does not exist in the current contex
Any help would be appreciated.
In some programming languages, a context is usually defined by { and }, meaning that given this:
{
int a = ...
}
a exists specifically within that block. Assuming that no other variable named a has been declared outside the braces, doing something like so:
{
int a = ...
}
print(a)
Will result in a fault, since a no longer exists.
In your case for instance, you are declaring the following variable: Centimeter c = new Centimeter();. Notice that this is enclosed within the do...while scope, so it exists only in there. Thus, when you try to access your variable from another method, which has its own scope, you get the exception you are getting.
To start solving the issue, you should move the 3 methods getMeterst, Remainder and Printout in their appropriate class, which is Centimeter.
I would recommend you start by looking at some tutorials, since you have other issues with your code.
As pointed out by #user2864740, different languages treat scopes differently. Taking Javascript in consideration:
function hello()
{
{
var i = 44;
}
{
alert(i);
}
}
Yields an alert with the value of 44.
However, the code below does not compile in C#:
private static void Hello()
{
{
int i = 0;
}
{
Console.WriteLine(i); //The name i does not exist in the current context.
}
}
you've got a lot of issues with scope in your code, when you declare something, it can (as a rule) only be accessed inside whatever set of brackets you declare it in, so when you try and access c and cmremainand things like that without specifying their location or accessing them correctly you get errors like this.
I have working code below, but feel free to ask any extra questions as to 'why' this works.
using System;
namespace Conv
{
public class Centimeter
{
public int cmvar;
public Centimeter()
{
cmvar = 0;
}
}
//primary const to be added
public class MeterToCenti
{
public static void Main()
{
char choice;
char n = 'n';
do
{
Centimeter c = new Centimeter();
Console.WriteLine("enter value in centimeters");
c.cmvar = int.Parse(Console.ReadLine());
Printout(c);
Console.WriteLine("Do you want to continue? (y/n)");
choice = Console.ReadKey().KeyChar;
Console.WriteLine();
}
while (choice != n);
}
public static int getMeters(Centimeter c)
{
int meters = c.cmvar / 100;
return meters;
}
public static int Remainder(Centimeter c)
{
int cmremain = c.cmvar % 100;
return cmremain;
}
public static void Printout(Centimeter c)
{
Console.WriteLine("{0} Meters and {1} Centimeters", getMeters(c), Remainder(c));
}
}
}
you need to learn oriented object programming before programming any oop language.
Basic is good but polute your mind by not thinking object, but sequencial...
Here is your code fixed
using System;
namespace Conv
{
public class Centimeter
{
public int cmvar;
public Centimeter()
{
cmvar = 0;
}
public Centimeter(int mm)
{
cmvar = mm;
}
public int getMeterst()
{
return cmvar / 100;
}
public int Remainder()
{
return cmvar % 100;
}
public void Printout()
{
Console.WriteLine("{0} Meters and {1} Centimeters", this.getMeterst(), this.Remainder());
}
}
public class MeterToCenti
{
public static void Main()
{
char choice;
char n = 'n';
do
{
Console.WriteLine("Do you want to continue? (y/n)");
choice = Console.ReadKey().KeyChar;
Console.WriteLine(); // for pure design needs
Centimeter c = new Centimeter();
Console.WriteLine("enter value in centimeters");
c.cmvar = int.Parse(Console.ReadLine());
c.Printout();
}
while (choice != n);
}
}
}

I need a simple and elegant user validation technique for a c# console application

Coming from a procedural background, I'm running into a conceptual block while designing a menu-based console application and user input validation. My goal is to display a menu that launches other processes. I want to limit user input to 1, 2, or 3 at the menu.
In a procedural language, I would do something like this pseudocode:
10 print "Make a choice"
20 choice = [dataFromKeyboard]
30 if choice < 4 && choice > 0
40 then 10
50 else 60
60 process valid choices
and no matter what I try, I can't get that out of my head while designing an OO program. Consider (simplified to include only 3 menu items):
class Menu
{
public static void Main(String[] args)
{
DisplayMenu thisdm = new DisplayMenu;
int menuChoice = thisdm.displayMenu();
ProcessMenu thispm = new ProcessMenu();
thispm.processMenu(menuChoice);
}
}
class DisplayMenu
{
public int displayMenu()
{
Console.WriteLine("1 - foo3");
Console.WriteLine("2 - foo2");
Console.WriteLine("3 - foo3");
Console.WriteLine("choose");
String choice = Console.ReadLine();
int intChoice = Convert.ToInt32(choice);
return intChoice;
}
}
class ProcessMenu
{
public void processMenu(int choice)
{
switch(choice)
{
case 1:
foo1();
break;
case 2:
foo2();
break;
case 3:
foo3();;
break;
default:
Console.WriteLine("Invalid selection. Please select 1, 2, or 3.");
break;
}
}
}
So here's where I'm stuck. I just can't wrap my head around a simple and elegant way validate my user input that's from an OO rather than procedural standpoint.
Assuming I do the validation in the DisplayMenu, I would be validating after the input is read. But if it turns out to be invalid, how do I re-ask for valid input, since I've already called displayMenu method from Main?
I've been playing with while loops for about an hour, something like this:
intChoice = 0;
[print the menu]
while ((intChoice<1) || (intChoice>3))
Console.WriteLine("Please make a valid choice from the menu");
choice = Console.ReadLine();
etc.
but can't seem to find the sweet spot where I can control user input.
I suspect it's because I'm thinking to procedurally, and not object-oriented enough. Anyone have any tips or input to help me wrap my head around this?
Expanding on #AlexeiLevenkov's suggestion of "turning your classes 90 degrees", I went a step further and created this example of a "Modular" console Application:
class Program
{
static void Main(string[] args)
{
//Retrieve all Module types in the current Assembly.
var moduletypes = Assembly.GetExecutingAssembly()
.GetTypes()
.Where(x => x.IsSubclassOf(typeof(ConsoleModule)));
//Create an instance of each module
var modules = moduletypes.Select(Activator.CreateInstance)
.OfType<ConsoleModule>()
.OrderBy(x => x.Id)
.ToList();
int SelectedOption = -1;
while (SelectedOption != 0)
{
//Show Main Menu
Console.Clear();
Console.WriteLine("Please Select An Option:\n");
modules.ForEach(x => Console.WriteLine(string.Format("{0} - {1}", x.Id, x.DisplayName)));
Console.WriteLine("0 - Exit\n");
int.TryParse(Console.ReadLine(), out SelectedOption);
//Find Module by Id based on user input
var module = modules.FirstOrDefault(x => x.Id == SelectedOption);
if (module != null)
{
//Execute Module
Console.Clear();
module.Execute();
Console.WriteLine("Press Enter to Continue...");
Console.ReadLine();
}
}
}
ConsoleModule class:
public abstract class ConsoleModule
{
public int Id { get; set; }
public string DisplayName { get; set; }
public abstract void Execute();
}
Some sample Modules:
public class EnterUserNameModule : ConsoleModule
{
public EnterUserNameModule()
{
Id = 2;
DisplayName = "User Name";
}
public static string UserName { get; set; }
public override void Execute()
{
Console.WriteLine("Please Enter Your Name: ");
UserName = Console.ReadLine();
}
}
public class HelloWorldModule: ConsoleModule
{
public HelloWorldModule()
{
Id = 1;
DisplayName = "Hello, World!";
}
public override void Execute()
{
Console.WriteLine("Hello, " + (EnterUserNameModule.UserName ?? "World") + "!");
}
}
public class SumModule: ConsoleModule
{
public SumModule()
{
Id = 3;
DisplayName = "Sum";
}
public override void Execute()
{
int number = 0;
Console.Write("Enter A Number: ");
if (int.TryParse(Console.ReadLine(), out number))
Console.WriteLine("Your number plus 10 is: " + (number + 10));
else
Console.WriteLine("Could not read your number.");
}
}
Result:
It uses a little bit of reflexion to find all types deriving from ConsoleModule in the current assembly, then shows a menu with all these options (which are actually properties in this class), and calls the Execute() method when an appropiate option is selected. Much more towards OO way of thinking.
Make your processMenu function return some kind of indicator. You could use exceptions for this instead, but that's overkill.
public bool processMenu(int choice)
{
....
}
If the choice was acceptable, then return true, otherwise return false. Then:
public static void Main(String[] args)
{
DisplayMenu thisdm = new DisplayMenu;
ProcessMenu thispm = new ProcessMenu();
int menuChoice;
do {
menuChoice = thisdm.displayMenu();
} while( !thispm.processMenu(menuChoice) );
}
The way you are doing should be changed. Anyhow, for the same as your question, this works out:
DisplayMenu thisdm = new DisplayMenu();
int menuChoice = -1;
while (menuChoice < 1 || menuChoice > 3)
{
Console.WriteLine("enter valid choice");
menuChoice = thisdm.displayMenu();
}
ProcessMenu thispm = new ProcessMenu();
thispm.processMenu(menuChoice);
the code like:
class Program
{
static void Main(string[] args)
{
DisplayMenu thisdm = new DisplayMenu();
ProcessMenu thispm = new ProcessMenu();
thisdm.displayMenu();
int menuChoice = thispm.GetChoice();
thispm.processMenu(menuChoice);
Console.Read();
}
}
class DisplayMenu
{
public void displayMenu()
{
Console.WriteLine("1 - foo3");
Console.WriteLine("2 - foo2");
Console.WriteLine("3 - foo3");
Console.WriteLine("choose");
}
}
class ProcessMenu
{
public int GetChoice()
{
String choice = Console.ReadLine();
int intChoice = Convert.ToInt32(choice);
while (!Validate(intChoice))
{
Console.WriteLine("Invalid selection. Please select 1, 2, or 3.");
choice = Console.ReadLine();
intChoice = Convert.ToInt32(choice);
}
return intChoice;
}
public void processMenu(int choice)
{
switch (choice)
{
case 1:
//foo1();
break;
case 2:
//foo2();
break;
case 3:
//foo3(); ;
break;
default:
//Console.WriteLine("Invalid selection. Please select 1, 2, or 3.");
break;
}
}
private int[] forChoices=new int[]{1,2,3};
private bool Validate(int choice)
{
if(forChoices.Contains(choice))
{
return true;
}
return false;
}
}

Not all code paths return a value with output parameter in method

I'm practicing building a dummy application and I'm trying to take pass in an enum as a parameter and have an integer output parameter that will be used to set a member variable (BillsOwed). I have two specific questions: Why is it that ComputeRetirementBenefitCost tells me that my variable must be assigned to before control leaves the current method and why isn't ComputeRetirementBenefitCost accessible where I have marked in my comments? Any and all prudent future design recommendations are welcome :)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GivePromotions
{
//Different Employees in the EmpType enum extend this class
public abstract class Employee
{
public int EmployeeId { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
public DateTime DateHired { get; set; }
public RetirementPackage.RetirementPackageType PackageType { get; set; }
public EmpType Employeetype { get; set; }
public int NetSalary { get; set; }
//I'd like to set the output of ComputeRetirementBenefitCost
//in the member below but Intellisense doesn't pick it up
//on two lines for space, commented because it doesn't work
//int billsOwed = Employee.RetirementPackage
//.ComputeRetirementBenefitCost(Employee.EmpType,out benefitCost)
public virtual void DisplayInformation()
{
Console.WriteLine("Employee information: ");
Console.WriteLine("EmployeeId = {0} ", EmployeeId);
Console.WriteLine("Last name = {0} ", LastName);
Console.WriteLine("First name = {0} ", FirstName);
Console.WriteLine("Date hired = {0} ", DateHired);
Console.WriteLine("Salary = {0} ", NetSalary);
}
public enum EmpType
{
Janitor,
President,
Manager
}
//an Employee 'has-a' Retirement package
public class RetirementPackage
{
public enum RetirementPackageType
{
Basic,
Gold,
Silver,
Platinum,
Black
}
//method of choice here
//ERROR: Output parameter 'benefitCost' must be assigned to before control
//leaves the current method
public void ComputeRetirementBenefitCost(Employee.EmpType e, out int benefitCost)
{
switch (e)
{
case Employee.EmpType.President:
benefitCost = 100000;
break;
case Employee.EmpType.Manager:
benefitCost = 5000;
break;
case Employee.EmpType.Janitor:
benefitCost = 1000;
break;
}
}
}
}
}
ERROR: Output parameter 'benefitCost' must be assigned to before control:
You have to add a "default:" to your switch or set a value outside your switch as it can be that none of your three cases is hit.
and why isn't ComputeRetirementBenefitCost accessible
Fixing the first will fix this one.
Use crtl+shif+B to build and read the errors and warnings in the error list view. Usually they tell you exactly what is wrong.
In the method ComputeRetirementBenefitCost it looks like you handled all possible code flows, because enum Employee.EmpType has three different definitions and you covered all three all them. But this is not true. From MSDN Enumeration Types (C# Programming Guide):
It is possible to assign any arbitrary integer value to meetingDay. For example, this line of code does not produce an error: meetingDay = (Days) 42.
In your case I can call your method like this
int benefitCost = 0;
ComputeRetirementBenefitCost( (Employee.EmpType) 500, out benefitCost);
And in this case I will be out of your code flow, so benefitCost will not be initialized. You can change implementation like this:
public void ComputeRetirementBenefitCost(Employee.EmpType e, out int benefitCost)
{
switch (e)
{
case Employee.EmpType.President:
benefitCost = 100000;
break;
case Employee.EmpType.Manager:
benefitCost = 5000;
break;
case Employee.EmpType.Janitor:
benefitCost = 1000;
break;
default:
throw new ArgumentOutOfRangeException("e");
}
}
The second problem - it looks like you are trying to invoke ComputeRetirementBenefitCost as a static method, but it is not static, so just add a static keyword to it.

how to store types as variables and use them in parameters' type?

class constType
{
public static const Type messageType = typeof(int); // HOW TO DO THIS? 1st mark
public string[] GetArraySomehow()
{
return new string[sizeof(messageType)]; // HOW TO DO THIS? 2nd mark
}
}
class testTypeInClass
{
public void test(constType.messageType message) // HOW TO DO THIS? 3rd mark
{
}
}
Okay so this is really weird and strange I know but how can I do this?
1st mark: I have to store int's type as const variable and use it laterç
2nd mark: I have to get stored type's size (how many bytes does it equal?)
3rd mark: I have to use it as a parameter type.
Well Why I have to do this such thing:
I have to store a type (not so wide, just I know I'll use int8,16,32 etc)
and have to know what exactly bytes does it equal (1,2,4 etc..);
well first of all I have a method in one of my classes which uses switch statement and:
like this:
public string test (int messageIndex)
{
switch (messageIndex)
{
case 0:
return "etc.. etc..";
case 1231412:
return "whatever";
}
}
Firstly I had some method like this:
public int fixForSwitchStatement(byte[] messageIndex)
{
byte[] RValue = new byte[4];
for (int i = 0; i <= messageIndex.Length - 1; i++)
{
RValue[i] = messageIndex[i];
}
for (int i = messageIndex.Length; i <= 4 - messageIndex.Length - 1; i++)
{
RValue[i] = 0;
}
return BitConverter.ToInt32(RValue, 0);
}
I was passing byte or short to switch statement then I was converting to int (int was a specified type for me) and I wanted to make a redesign like this.
public string test (/* [what's the case limit? that I've determined?] */ messageIndex)
{
switch (messageIndex)
{
case 0:
return "etc.. etc..";
case 1231412:
return "whatever";
}
}
Because I don't want to use fixSwitch... method anymore. I just need a specified type for all of these concept.
Why I have to use fixSwitch instead of typecasting like (int)somethingByte?
Well in my one of classes there is a thing called communicationSize, its the messageIndex thing's maximum size in byte(s) that I have to declare. This is for my server-client project. There is a messageIndex thing being used as a request index what server and client requests from each other. And I'm limiting it with byte(s). For save some data space from connection.
// still is being written
I'm not sure what the goal is and the question has been edited in the meantime but heres some example code using generics that may help you further.
class constType<T> where T : struct
{
public T GetT()
{
return new T();
}
public string[] GetArraySomehow()
{
var len = Marshal.SizeOf(typeof(T));
return new string[len];
}
}
class testTypeInClass
{
public void test<T>(T message) where T : struct
{
}
}
class MyClass
{
void Test()
{
var constType = new constType<int>();
var typeInClass = new testTypeInClass();
var t = constType.GetT();
typeInClass.test(t);
}
}

Categories