Dumbo
Dumbo

Reputation: 14102

How to declare Types in c#

I am not sure what is the correct name for what I am looking for!

What I am trying to do is to make a method to update a status bar text, and color it as red if it is a error message or green if it is a success message:

public void UpdateStatus(string message, MessageType type)
{
      if(type == MessageType.Error)
      {
           statusText.Text = message;
           statusText.ForeColor = Color.Red;
      }

      if(type == MessageType.Success)
      {
           statusText.Text = message;
           statusText.ForeColor = Color.Green;
      }
}

And here is the MessageType

public class MessageType
{
    class Error
    {
       //What to do here?
    }

    class Success
    {
        //What to do here?
    }
}

So how can I define this MessageType class, and how is it called? Interface? Enum? what??

Thanks.

P.S: I know I can just use Color as the second parameter for UpdateStatus method I wrote, but I want to learn how to make it like what I said.

Upvotes: 1

Views: 190

Answers (7)

Samuel Slade
Samuel Slade

Reputation: 8613

If you decide to go with the use of an enum, using:

public enum MessageType
{
    Failure,
    Success
}

... then you can handle it using a switch-case, like so:

public void UpdateStatus(string message, MessageType type)
{
   statusText.Text = message;

   switch (type)
   {
       case MessageType.Error:
           statusText.ForeColor = Color.Red;
           break;

      case MessageType.Success:
           statusText.ForeColor = Color.Green;
           break;
   }
}

Upvotes: 1

ClearCarbon
ClearCarbon

Reputation: 459

I think you want an enum should be something like

public enum MessageType { Error, Success };

Take a look http://msdn.microsoft.com/en-us/library/sbbt4032(v=vs.71).aspx for more info.

Upvotes: 1

George Duckett
George Duckett

Reputation: 32418

public enum MessageType {Error, Success};

Upvotes: 1

Paul Sasik
Paul Sasik

Reputation: 81429

You probably want an enum:

public enum MessageType
{
    Error,
    Success
}

Then in code that uses the enum you would do something like:

if (msg == MessageType.Error)
    // show error info
else
    // show success info

Upvotes: 1

Femaref
Femaref

Reputation: 61427

You are looking for an enum in this case:

public enum MessageStatus
{
  Failure,
  Success
}

Upvotes: 1

Henk Holterman
Henk Holterman

Reputation: 273169

I think you just need an enum:

public enum MessageType { Error, Success }

and then your if(type == MessageType.Error) just works.

Upvotes: 3

SLaks
SLaks

Reputation: 887195

You're trying to make an enum type:

public enum MessageType {
    Success,
    Error
}

Upvotes: 5

Related Questions