Anirudh Goel
Anirudh Goel

Reputation: 4721

assign an enum value to an enum based on a condition in c#

i have a class and have declared an enum in it like

public enum file_type {readonly, readwrite, system}

Now based on a condition i want to set the enum file_type to a value something like

if("file is markedreadonly")
   file_type = readonly;

is it possible to do so in c#

Upvotes: 0

Views: 5660

Answers (4)

Malcolm
Malcolm

Reputation: 410

You can definitely do this, almost exactly as you indicated. Note: I've changed casing to conform to accepted C# coding guidelines.


public enum FileType { ReadOnly, ReadWrite, System }

...

FileType fileType; FileInfo file = new FileInfo("C:\full\path\to\file"); if (file.IsReadOnly) fileType = FileType.ReadOnly

Also, check out System.IO.FileAccess and System.IO.FileAttribute enums. They may provide you with a standard implementation that is more suitable. Personally, I prefer to use a system type rather than "rolling my own" -- less work and more easily understood by other programmers.

HTH

Upvotes: 0

nickd
nickd

Reputation: 4021

The enums themselves behave more like types. You need a variable of type file_type which you can then assign to file_type.readonly

public enum FileType
{
    ReadOnly,
    ReadWrite,
    System
}

FileType ft;

if (...) ft = FileType.ReadOnly;

Upvotes: 0

John Saunders
John Saunders

Reputation: 161791

Your syntax is wrong. file_type is a type, not a variable. Also, you need @readonly, since readonly is a reserved word.

Upvotes: 1

SolutionYogi
SolutionYogi

Reputation: 32243

By writing file_type = readonly, you are trying to change the definition of an Enum at runtime, which is not allowed.

Create variable of type file_type and then set it to readonly.

Also, please use .NET naming standards to name your variable and types. Additionally for Enums, it is recommended to have a 'None' enum as the first value.

public enum FileType { None, ReadOnly, ReadWrite, System}

FileType myFileType = FileType.None;

if( //check if file is readonly)
    myFileType = FileType.ReadOnly;

Upvotes: 7

Related Questions