How to Assign Enum to Variable

How to Assign Enum to Variable

How to assign new variable from declared enum

public enum FontStyle
{
 Regular = 0;
 Bold =1;
 Italic = 2
}
// dont know what Type to cast it :/
TYPE fontstyle = FontStyle.Bold;

I am not sure which TYPE to cast it, It is contained within System.Drawing class.

6

4 Answers

It's of type FontStyle i.e. Enums are first class types.

public enum FontStyle
{
    Regular = 0;
    Bold =1;
    Italic = 2
}

// No need to cast it
FontStyle fontstyle = FontStyle.Bold;

Edit: Perhaps you have code like this:

if(1 == 1)
    FontStyle fontstyle = FontStyle.Bold;    

for your error (Embedded statement cannot be a declaration or labeled statement) surround your code in a block statement e.g.

if(1 == 1)
{
    FontStyle fontstyle = FontStyle.Bold;    
}
0

Enums are types, so your variable should be of the type FontStyle:

FontStyle fontstyle = FontStyle.Bold;
3

Make sure you use , to separate enum elements, not ; ... like

enum Days {Sat, Sun, Mon, Tue, Wed, Thu, Fri};

Make sure you don't have a class vs property name mixing in your code...

    private void Form1_Load(object sender, EventArgs e)
    {
        // dont know what Type to cast it :/
        System.Drawing.FontStyle fontstyle = FontStyle.Bold;
        MessageBox.Show(fontstyle.ToString());
    }

returns "Bold" :)...

Make sure to have

using System.Drawing;

and that you don't have the enum declared in the same location where you said you cannot create the enum object.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Chloe Bennett
Author

Chloe Bennett

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.