How can I use Enum in switch statement - c#

What I am trying to do is detecting the type of "item" and using it inside of a switch statement and based on that, choosing correct equipment slot.
My code:
public EquipmentSlot WeaponSlot;
public EquipmentSlot ChestplateSlot;
public EquipmentSlot LeggingsSlot;
public EquipmentSlot HelmetSlot;
public void EquipItem(Item item)
{
EquipmentSlot chosenSlot = null;
switch(item.type)
{
case item.type.weapon:
chosenSlot = WeaponSlot;
break;
case item.type.chestplate:
chosenSlot = ChestplateSlot;
break;
case item.type.leggings:
chosenSlot = LeggingsSlot;
break;
case item.type.helmet:
chosenSlot = HelmetSlot;
break;
}
chosenSlot.EquippedItem = item;
}
Item class:
public enum Type
{
weapon,
chestplate,
leggings,
helmet
}
public Type type;
This error is showing up:
error CS0176: Member 'Item.Type.helmet' cannot be accessed with an instance reference; qualify it with a type name instead
(four times for each case in switch)

Instead of case item.type.weapon: it should be case Item.Type.weapon:

try this
switch (item.type)
{
case Type.weapon:
chosenSlot = WeaponSlot;
break;
case Type.chestplate:
chosenSlot = ChestplateSlot;
break;
.....
}
but it will be much more readable if you rename Type to ArmoryType for example

Related

Get Array values using a class in c#

i have declared 2 string values eg: ChName1, ChName2 and 2 int values eg: Delay1, Delay2 in the settings.
i would like to implement an array in class so life will be more easier. can somebody correct my code with necessary explanations
public class GetDefaultValues
{
public string Name[int i]
{
get
{
switch (i)
{
case 0:
return Name.Properties.Settings.Default.ChName1;
case 1:
return Name.Properties.Settings.Default.ChName2;
default:
return "Not Implemented";
}
}
set
{
switch (i)
{
case 0:
{
Name.Properties.Settings.Default.ChName1 = value;
break;
}
case 1:
{
Name.Properties.Settings.Default.ChName2 = value;
break;
}
}
Name.Properties.Settings.Default.Save();
}
}
public int Value[int i]
{
get
{
switch (i)
{
case 0:
return Name.Properties.Settings.Default.Delay1;
case 1:
return Name.Properties.Settings.Default.Delay2;
default:
return 0;
}
}
set
{
switch (i)
{
case 0:
{
Name.Properties.Settings.Default.Delay1 = value;
break;
}
case 1:
{
Name.Properties.Settings.Default.Delay2 = value;
break;
}
}
Name.Properties.Settings.Default.Save();
}
}
}
then in my main code i could do like this
GetDefaultValues Vlues = new GetDefaultValues();
Vlues.Name[0] = "SomeName";
string SomeString = Vlues.Name[1];
Vlues.Value[0] = 125;
int SomeInt = Vlues.Value[1];
this code is generating errors in my code.
Error 2 Bad array declarator: To declare a managed array the rank
specifier precedes the variable's identifier. To declare a fixed size
buffer field, use the fixed keyword before the field type
will be happy if i could know why??
please help!!
I would recommend not to use properties for this because properties should not have that logic. You should use methods instead.
This could be look like this for example (just added the name as a sample).
public class GetDefaultValues
{
public bool SetName(int i, string value)
{
switch (i)
{
case 0:
{
Name.Properties.Settings.Default.ChName1 = value;
break;
}
case 1:
{
Name.Properties.Settings.Default.ChName2 = value;
break;
}
default:
return false;
}
Name.Properties.Settings.Default.Save();
return true;
}
public string GetName(int i)
{
switch (i)
{
case 0:
return Name.Properties.Settings.Default.ChName1;
case 1:
return Name.Properties.Settings.Default.ChName2;
default:
return "Not Implemented";
}
}
}
This would be called like this
GetDefaultValues Vlues = new GetDefaultValues();
bool success = Vlues.SetName(0, "SomeName");
string SomeString = Vlues.Name(1);
You can make the SetName method a void method if you don't want to have the info if it worked or not.

Public Int Error

I am trying to create a menu that goes to different sections without using a class but I am receiving errors using public int.
public int menu()
Console.WriteLine("Select a category to view");
Console.WriteLine("");
Console.WriteLine("1.Groceries");
Console.WriteLine("2.Electronics & Appliances");
Console.WriteLine("3.Exit");
Console.ReadKey();
int User = int.Parse(Console.ReadLine());
switch (User)
{
case 1:
Console.WriteLine("...........Groceries...............");
break;
case 2:
Console.WriteLine("..............Electronics & Appliances............");
break;
case 3:
Console.WriteLine("...........Exit...............");
break;
}
Turning your function into a static void method solves the problem. And you are missing the { after the menu(). Following your paradigm the code would be:
namespace ConsoleApplication1
{
class Program
{
static void menu()
{
Console.WriteLine("Select a category to view");
Console.WriteLine("");
Console.WriteLine("1.Groceries");
Console.WriteLine("2.Electronics & Appliances");
Console.WriteLine("3.Exit");
Console.ReadKey();
int User = int.Parse(Console.ReadLine());
switch (User)
{
case 1:
Console.WriteLine("...........Groceries...............");
break;
case 2:
Console.WriteLine("..............Electronics & Appliances............");
break;
case 3:
Console.WriteLine("...........Exit...............");
break;
}
}
static void Main(string[] args)
{
menu();
}
}
}

how to take a value from an object and turn it to string?

public UcCard CardValue()
{
UcCard current = pack[index];
UcCard.Type cardvalue = 0;
current.Value = cardvalue;
edit:return current.Value.ToString(cardvalue);
//////return UcCard.ToString(cardvalue);
}
edit:now it says that it cannot convert the "***.UcCard.Type" to string
im getting the error "No overload for method 'ToString' takes 1 arguments"
what im trying to do is take a value from UcCard and then print it, now i know that UcCard is an object, but im not sure on how to take the value and transfer it to string
im new to coding so be gentle T_T i tried searching for an answer before posting but i just couldnt find an answer that fitted my need
also, this is where im trying to take the value from:
public int Volume
{
get
{
switch (lblValue.Text)
{
case "2": return 2;
case "3": return 3;
case "4": return 4;
case "5": return 5;
case "6": return 6;
case "7": return 7;
case "8": return 8;
case "9": return 9;
case "10":
case "K":
case "Q":
case "J": return 10;
case "A": return 1;
}
return 0;
}
}
Every class or struct in C# implicitly inherits the Object class.
This class contains the ToString method which is called when you prints out strings .
And you should customize it for your use AKA override it because the program will not guess what Attributes it should print not mention in what format.
(e.g from MSDN )
class Person
{
public string Name { get; set; }
public int Age { get; set; }
public override string ToString()
{
return "Person: " + Name + " " + Age;
}
}

string to constant type in c#

We have constants defined in a static class along with functions like
public const string MSG_1 = "New error {0}"
public const string MSG_2 = "Random error occurred {1}"
public static string Message_ToForm(string MType, string[] vals)
public static GetNewType(string MType)
{
switch (MType)
{
case "MSG_1" : ...........
}
}
I require to call it from a program like
Message_ToForm("MSG_1", string[]);
How can I convert it to get the value of the constant from string type?
Basically, it should return me as "New error {0} when "MSG_1" is passed?
You might need a return type as String for your GetNewType
Suggestion:
If the constants are NOT reused and it if its ONLY for your lookup.
You could use a Dictionary to do the lookup
Dictionary<string, string> constValues = new Dictionary<string, string>()
{
{"MSG_1", "New error {0}"},
{"MSG_2", "Random error occurred {1}"}
};
public string GetNewType(string MType)
{
if (constValues.ContainsKey(MType))
return constValues[MType];
return string.Empty;
}
I'm really confused with your question, but think that's what you're looking for:
public static string GetNewType(string MType)
{
switch (MType)
{
case "MSG_1": return MSG_1;
case "MSG_2": return MSG_2;
default: throw new ArgumentException("MType");
}
}
But I must say - that's really bad approach! You should rethink your design.
I would create a MessageType enumeration and switch based on that.
enum MessageType
{
None = 0,
Msg1,
Msg2
}
public static string GetNewType(MessageType MType)
{
string msg = string.Empty;
switch (MType)
{
case MessageType.Msg1:
msg = MSG_1;
break;
case MessageType.Msg2:
msg = MSG_2;
break;
}
return msg;
}
You were missing a return type on your method. I believe this is what you want.
static string GetNewType(string MType)
{
switch (MType)
{
case "MSG_1" :
return MSG_1;
case "MSG_2":
return MSG_2;
}
return "";
}
But is there are reason your strings are saved as constants in variables? Couldn't you just return the strings in the switch? Like this:
switch (MType)
{
case "MSG_1" :
return "New error {0}";
case "MSG_2":
return "Random error occurred {1}";
}
Create a static readonly ReadOnlyDictionary property populated with your 'constants':
private static readonly System.Collections.ObjectModel.ReadOnlyDictionary<string, string> _msgDictionary =
new System.Collections.ObjectModel.ReadOnlyDictionary<string, string>(
new Dictionary<string, string>()
{
{ "MSG_1", "New error {0}" },
{ "MSG_2", "Random error occurred {1}" }
});
public static System.Collections.ObjectModel.ReadOnlyDictionary<string, string> Messages
{
get { return _msgDictionary; }
}
Then usage:
var msg = Messages["MSG_1"];
public static GetNewType(string MType)
{
string MType = yourClass.MSG_1
switch (MType)
{
case yourClass.MSG_1
break;
....
default:
// Code you might want to run in case you are
// given a value that doesn't match.
break;
}
}
I strongly recommend using the out of the box .NET localization feature. You simply add a resource file to your project and put all your string messages into it, the resource file is like a key value pair of string resources, the IDE automatically creates a property for each string message which you can use in your code.
Check this How to use localization in C# for more details.

Classes with String Switches

class AddItemOption
{
//Fields that contain class data
string input = Console.ReadLine();
//Methods that define class functionality
public string myFunction(string Value)
{
switch (input)
{
case "Umbrella":
Console.WriteLine("Umbrella is selected");
break;
case "Rain Coat":
Console.WriteLine("Raincoat is selected");
break;
case "Boots":
Console.WriteLine("Boots is selected");
break;
case "Hood":
Console.WriteLine("Hood is selected");
break;
default:
Console.WriteLine("Input not reconized, please choose another item");
break;
}
}
I get the error "Not all code paths return a value". It is from myFunction(string Value). I'm not sure how to return this, or what to put in the parameter to get it to work. Do I need something below it too? I am new to classes. Please tell me if I'm doing this all wrong or if that is where the switch statement should go!
public AddItemOption(string input)
{
}
FROM Shyju I changed it to:
class AddItemOptionOne
{
//Fields that contain class data
string input = Console.ReadLine();
//Methods that define class functionality
public string myFunction(string Value)
{
switch (input)
{
case "Key Chain":
return "Key Chain is selected";
break;
case "Leather Armor":
return "Leather Armor is selected";
break;
case "Boots":
return "Boots is selected";
break;
case "Sword":
return "Sword is selected";
break;
default:
return "Input not reconized, please choose another item";
break;
}
}
However, it does not recognize the breaks. "Unreachable Code Detected"
Your method has a return type of string. That means your method should always return some string. But you are not returning a string. instead you are Writing it to the console using WriteLine method.
So Change
Console.WriteLine("Umbrella is selected");
to
return "Umbrella is selected";
OR
You can change your method's return type to void.
public void myFunction(string Value)
{
//your current fancy stuff here
Console.WriteLine("My method dont have a return type");
}
EDIT : AS per the question edit.
return statement will take the control out from your method. that means the next line (break) won't be executed. So remove the break statement.
case "Key Chain":
return "Key Chain is selected";
Well... You don't return anything from your function, so change it to
public void myFunction(string Value)
Try this:
class AddItemOptionOne
{
//Methods that define class functionality
public string myFunction(string input)
{
string result = string.Empty;
switch (input)
{
case "Key Chain":
result = "Key Chain is selected";
break;
case "Leather Armor":
result = "Leather Armor is selected";
break;
case "Boots":
result = "Boots is selected";
break;
case "Sword":
result = "Sword is selected";
break;
default:
result = "Input not reconized, please choose another item";
break;
}
return result;
}
}

Categories