[Home]
[Edit this page]
[Recent Changes]
[Special Pages]
[Help]
CSharpEnum
Values can be easily converted to ?string using the ToString() method.
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
CSharpEnum
(C#) enum
Keyword to define an enumeration.Values can be easily converted to ?string using the ToString() method.
Simple example
This code shows how to use and display enumeration values
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
//The enumeration
enum MyEnum { paper, rock, scissors }
static void Main()
{
//Show the three enumation values on screen without using a cast
const MyEnum myPaper = MyEnum.paper;
const MyEnum myRock = MyEnum.rock;
const MyEnum myScissors = MyEnum.scissors;
Console.WriteLine(myPaper.ToString() + '\t' + myRock.ToString() + '\t' + myScissors.ToString());
//Show the three enumation values on screen using a cast
for (int i = 0; i < 3; ++i)
{
MyEnum myEnum = (MyEnum)i;
Console.Write(myEnum.ToString() + '\t');
}
//Wait for key input
Console.ReadLine();
}
}
}
Paper-rock-scissors example
In this example below, a paper-rock-scissors game is player. The enumeration consists of paper, rock and scissors.
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
enum myEnum { paper, rock, scissors }
static void Main()
{
//Create instance of Random
Random myRandom = new Random();
//What do the players play?
myEnum player1 = (myEnum) myRandom.Next(3);
myEnum player2 = (myEnum) myRandom.Next(3);
Console.WriteLine("Player #1 plays: " + player1.ToString());
Console.WriteLine("Player #2 plays: " + player2.ToString());
//What is the outcome of the fight?
if (player1==player2)
{
Console.WriteLine("Draw!");
}
else if (
(player1==myEnum.paper && player2==myEnum.rock)
|| (player1==myEnum.rock && player2==myEnum.scissors)
|| (player1==myEnum.scissors && player2==myEnum.paper))
{
Console.WriteLine("Player #1 won!");
}
else
{
Console.WriteLine("Player #2 won!");
}
//Wait for key input
Console.ReadLine();
}
}
}
'enum' links
Code links
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
