.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
david stephan
Gaurav Pal
Post New Web Links

Enum != Enum

Posted By:      Posted Date: April 14, 2011    Points: 0   Category :.NET Framework

Enum is a value type, generally value types support IEquality however:

using System;

namespace ConsoleApplication1
	class Program
		enum Foo { On, Off };

		static void Main(string[] args)
			Enum enum1 = Foo.On;
			Enum enum2 = Foo.On;

			if (enum1 == enum2)
				Console.WriteLine("enum1 == enum2");
				Console.WriteLine("enum2 != enum2");

			if (0 == enum1.CompareTo(enum2))
				Console.WriteLine("enum1 is the same as enum2");
				Console.WriteLine("enum2 is not the same as enum2");


Results in "enum2 != enum2" and "enum1 is the same as enum2"!

View Complete Post

More Related Resource Links

How to cast integer values as an array of enum values?


Hello all!

I'm working with VS2010 Beta2, ASP.NET and Dynamic Data. I'm using VB but will certainly be happy to receive a C# example if necessary. Laughing

I used a few of Steve's examples (Writing Attributes and Extension Methods for Dynamic Data and Dynamic Data - Hiding Columns in selected PageTemplates) to create a custom property attribute to be applied to a dynamic data column and want it to accept an array of enum values (each value will represent a dynamic data page template where this column should not be displayed).  My new attribute works fine when I hardcode it like this, meaning the HideColumnIn attribute is properly populated with the array of enum values:

<HideColumnIn(PageTemplate.List, PageTemplate.Edit)> _
Public Property My_DD_Column As Object


However, I want to store the values to be used for the HideColumnIn in the DB as integer values that correspond to the

enum and switch need help

void Main()
	string t = "Vendor";
	switch (t)
		case PType.Client :
		case PartyType.Vendor :

public enum PType

When I try to run these code got error:  cannot implicitly convert type PType to string

If I change PType.Client to PType.Client.ToString() got error: A constant value is expected


how to use enum in class


hi there
in my class i have this code

  public enum userTypeID
            Superuser = 1,
            User = 2
        public userTypeID Tipo;

and i am trying to use with

int use= int.Parse(CLS_UserType.userTypeID.Superuser)

it return error because it is not possible cast int to enumeration
how can i do to get a value?

Comparing Enum values in a collection - BC42025: Access of shared member, constant member, enum mem


I am upgrading from asp1.1 to 2.0

I use collection classes to sort data (e.g in datagrids etc)


Enum newsFields
End Enum

Public Overloads Sub Sort(ByVal sortField As newsFields, ByVal isAscending As Boolean)
Select Case sortField
Case newsFields.title

Bug: Specifying values in the definition of an enum in Web Parts in subsites

Pardon the cumbersome title, but I wanted to make it as descriptive as possible! Anyway, I stumbled upon this bug and spent a good while trying to figure out what was wrong. I'm developing a WebPart for use in MOSS 2007. The WebPart in question is mostly unremarkable, but I was getting the following error when editing the WebPart properties: "Some of the properties for this Web Part cannot be displayed properly. For more information, see your site administrator." I've searched Google, Bing and Yahoo for this error and have found nothing, so hopefully this post will be of use to anyone else who searches for it. Turns out the problem was in the enumerator definition. It looked like this:   public enum KPIPalette { Grey = 1, Green, Blue, Orange }   The colour palettes of the components we're using started at 1, so I set the enumerator to do that also. SharePoint, however, had other ideas. The solution is to leave enumerator definitions out. When the number was required later in code, a 1 was added. Error begone, problem solved!

How to cast integer values to an array of enum values?

Hello all! I'm new to VB.NET (and OOP in general) and am struggling a bit...  I'm working with VS2010 Beta2, ASP.NET and Dynamic Data, however I'm thinking this question may be more related to VB so hopefully I've chosen the correct forum. I have a list of integer values stored in the DB and would like to cast them to an array of enum values so that they may be passed to my constructor.  The values in the DB directly correspond to the enum values.  Here is stripped down version of the code that hopefully highlights what I'm attempting to do:Private _pageTemplate() As PageTemplate Public Sub New(ByVal ParamArray pageTemplateArray As PageTemplate()) _pageTemplate = pageTemplateArray End Sub Public Enum PageTemplate Details = 1 Edit = 2 Insert = 3 List = 4 ListDetails = 5 End Enum What I'm having difficulty with is reading integer values from the DB and casting them to an array of PageTemplate() to be passed to the constructor above.  The integer values in the DB will be 1 through 5 to correspond to the enum values listed above.  Here is how I'm trying to build the ParamArray to be passed to the attribute constructor:Dim hideFieldsIn(-1) As PageTemplate Dim rowCount As Integer = -1 If reader.HasRows Then While reader.Read() rowCount += 1 ReDim hideFieldsIn(rowCount)

How to expose an enum type to a client via WCF if it isn't used as a param type in any service oper

Hi,   I want to 'expose' an enum type from my server via WCF so that my client can access it. This happens automagically if I use the enum as a parameter type within a service operation, however, what if the particular enum isn't part of any service operation?   In other words, I've defined serveral enums within my Server that are quite useful to my client (even though they don't appear in any of my paramter declarations for the service operations).   The only way I can get this to work is simply create dummy service operations that contains these enum's as arguments. The MEX page then exposes these types for my client to use, but this seems a bit naff.   Thanks   Paul.

Enum in WCF is throwing exception

wcf service method is returning a datacontract that contains an enum .The following error is thrown in the clientSystem.ServiceModel.CommunicationException was caught  Message="An error occurred while receiving the HTTP response to http://localhost:8731/Design_Time_Addresses/WCFTest3/Service1/. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details."  Source="mscorlib"  StackTrace:    Server stack trace:        at System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)       at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)       at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)       at System.ServiceModel.Channels.ClientReliableChannelBinder`1.RequestClientReliableChannelBinder`1.OnRequest(TRequestChannel channel, Message message, TimeSpan timeout, MaskingMode maskingMode)       at System.ServiceModel.Channels.ClientReliableChannelBinder`1.Request(Message message, TimeSpan timeout, MaskingMode maskingMode)       at System.ServiceModel.Channels.ClientReliableChannelBind

Details View Biding Custom Object with Enum properties fields

Hello, I'm trying to bind custom object to details view. The problem is that enum property fields are not show.Is there any way to show enum property fields in details view ?I put some example code below (I do not specify any rows mappings, they are generated dynamically because different kind of objects are bound to details view):// My object public class OrderItem { public ItemKindEnum unitemizedItemKind { get { return (ItemKindEnum)this.unitemizedItemKindID; } } ... } // Details view configuration <asp:DetailsView ID="dvOperationDetails" runat="server" DefaultMode="ReadOnly" ... />

Allow System.Enum and System.ValueType as parameter types in a custom attribute

This is a continuation from a Microsoft Connect posting: https://connect.microsoft.com/VisualStudio/feedback/details/507907/error-an-attribute-argument-must-be-a-constant-expression-etc-incorrectly-received-when-the-argument-is-of-type-enum I am replying to Karel Zikmund’s latest posting, dated 29/07/2010 at 12:57.   Thank you for your response Karel, but once again, I am afraid you are wrong: > > This is irrelevant: the same is true irrespective of whether the parameter type is System.Enum or System.Object. > It is actually relevant - Think how IL code for this code should look like: >    void MyMethod(System.Enum arg) { System.WriteLine(arg); } >    MyMethod(MyInt1Enum.One); >    Mymethod(MyInt4Enum.Two); I’ve looked at the generated IL. It looks exactly the same as it does if I change the parameter type to System.Object. This is also what I expected. What IL did you expect to be generated? > System.Object is passed by reference which is a fixed size (4 or 8 bytes on x86 or x64 arch respectively). Yes, and so is System.Enum (and System.ValueType). > Enums and value types are passed by value (unless they are boxed) and their size therefore has to be known at JIT time. Yes, but System.Enum and System.ValueType are both neither an enum type nor a value type — they are both reference types that

Data Binding RadioButton to enum via code


I was reading this solution on how to bind a RadioButton to a enum type, but in my special case I need to do it programmatically since I am generating a number of panels with 3 radiobuttons the number of which is only known runtime.

I tried this: 

Binding b = new Binding("CerradaBind");
        b.Mode = BindingMode.TwoWay;
        b.Source = _exp3Class;
        _gpuertas[i].BotonCerrada.SetBinding(_gpuertas[i].BotonCerrada.IsChecked, b);

But found out the IsChecked property is not what the Setbinding function expects, how should I do it?

Also, is there another way of binding directly to radiogroup instead of button by button?

LinqDataSource Using Enum in Where?


Not sure where the best place to ask this question is so I will ask it here.  I am trying to use the LinqDataSource ASP.NET 3.5 control and am having a problem with using the Where attribute.  I have a field that I want to filter on that is an Enumeration, however if I try to put the integer value in the Where attribute the page will not compile.  How do I use enum values in the Where attribute?

I have something like this:

public enum EventType
    Charger = 0,
    Location = 1,
    Scanner = 2


I want to filter the LinqDataSource like this:

<asp:LinqDataSource ID="DataSource1" runat="server"
        Where="EventType = 2" />

This won't work.  The EventType property is an instance of the enum type above.   


Assign a value to an enum "SSRS


Hi Everyone,

I am creating a report in SSRS.  When I pull in values from the database they come in as Enums.  Is there a way to assign values for these Enums?  For example,

0 = None
1 = Open Order
2 = Delivered
3 = Invoiced

Thanks in advance,


Dynamic Enum with intellisense?



I know this is asking alot...and as far as I know there is no way to do this..but I still tought that I whould ask you guys if you might some how figured this one out...

The thing is that I have a database-table that contains information about different user-roles...and I whould like to retrive each roles-name in an enum..and as the data changes in teh table I whould like the enum to change aswell...and I also whould like it to be possible to actually get intellisense once trying to access the enum..

I have looked at the following link and sulotion:


The problem with that as far as I have understod, is that I dont get the intellisense and the code kind of gets even harder to understand...since the whole point with enums is to make the code easy to understand..atleast as far as I know..

So any ideas?...I know this is sort of "madness"..but still worth a shot..

Thanks in advance!

How To get Data From Database in to C# Enum?


How can we get data from database into enum??

For e.g.

My database contains 100 tables.I want to use these table names into enum,so that if we added one more table ,
it will automatically add that table into this enum.Also ,if the table name changed internally, the name in enum also must affect....



Is this possible using DLL? Currently I am creating all enum mannually and creating DLL everytime...

But ,want to create it automatically..

If any one know pls reply me.

Thanks & Regards,

DataGridComboBoxColumn bound to an enum w/ text converter


I'm trying to get a DataGridComboBoxColumn to bind to a property that is an value of an enum.  If I use AutoGenerateColumns=True, it does it automatically.  I know that I shouldn't have to create a static resource.  With auto generating columns it shows the name of the enum value selected.  Those don't have spaces in them, but are well described; therefore, I'd also like to get a string version of it the enum.  Any ideas how to do this?  Even if we can just solve the first part of my question; that would be nice.

<DataGrid Grid.Row="2" ItemsSource="{Binding Path=Users}" AutoGenerateColumns="False" >
        <DataGridTextColumn Header="Username" Binding="{Binding Name}"/>
        <DataGridTextColumn Header="Password" Binding="{Binding Password}"/>
        <DataGridComboBoxColumn Header="User Type" SelectedItemBinding="{Binding Type}" />

ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend