c# enums: can they take members and functions like java enums? - c#

in java it is possible to give an enum a constructor as well as member variables and functions.
i was wondering if something like this is possible in c# enums as well. if so, how?
thanks a lot!

The only way to do something similar to this is to use extension methods, which can make it appear as though the enumeration has member methods.
Other than that, you could create a companion struct type to your enumeration that has a property for the enumeration value and then adds additional properties and methods to support that value.

It is not. In Java, enumerations are a class while in C#, an enumeration is just syntactic sugar wrapping a primitive type.

Enums are strongly typed constants. They are essentially unique types that allow you to assign symbolic names to integral values. In the C# tradition, they are strongly typed, meaning that an enum of one type may not be implicitly assigned to an enum of another type even though the underlying value of their members are the same. Along the same lines, integral types and enums are not implicitly interchangable. All assignments between different enum types and integral types require an explicit cast.
You can't use member variables or constructors in an enum. Maybe what you are looking for is an struct.
A struct type is a value type that can contain constructors, constants, fields, methods, properties, indexers, operators, events, and nested types. The declaration of a struct takes the following form:

You could imitate the Java TypeSafe enum pattern (what was so common in Java before enum was introduced in Java 5 to address it):
See Item 21 here (warning, PDF link) for a description.
You would do this if the object functionality was more important than the switch functionality, since in C# you can get the type saftey without it (which you couldn't in Java before 5).

One thing I've always loved to do is to use the Description attribute on my enums so I can store 3 values of my enum easily
Public Enum States
{
[Description("Florida")]
FL = 124
}
And then I had a class that easily reads to/from the description attribute so I could store a whole database code table in an enum file. Aside from all the posters bringing up extension methods you could use attributes to drive log with your enum classes.
You would still need to leverage another class to actually do something with the enum but you could use attributes to add more depth to your enum instead of just having the key/value pair that it basically is.

Not directly but you can use Extension methods to provide similar functionality

This is not possible in C#. Enums can only have name / value members.

As far as I am aware, no you can't in C#. Although why would you want too? Seems a bit of an odd thing to attach variables and functions too!

You can define extension methods for enum types, but you can't add state to enums, since enums are represented as simple integer types internally, and there'd be nowhere to store the state.

Related

Can I cast an int into a C# enum type?

I have an enum (of underlying type int) with two values, and a method that takes a parameter of that type. Is it possible to cast any int value to my enum type and pass it to the method? If so, what is the advantage of an enum? Isn't it supposed to restrict the choice of values available?
class Program
{
public void Greeting(MyCode code)
{
Console.WriteLine(code);
}
static void Main(string[] args)
{
var p = new Program();
var m = new MyCode();
m = (MyCode) 3;
p.Greeting(m);
}
}
public enum MyCode:int
{
Hello =1,
Hai
}
Yes, you can cast any value of the underlying type. The enum type is not a restrictive type in that sense.
The advantages of using enums are:
Readability
Correctness when you don't explicitly cast
Ability to access values via reflection etc
I agree that a more type would be useful too, but it doesn't exist in C#. You can build your own class-based "pseudo-enums" in C# which allow for a restricted set of values (using a private constructor), but:
You can't make them non-nullable
You can't switch on them
You can't use them for constant values (such as optional parameter defaults)
The value will always be a reference, which can impact on memory usage (compared with an enum with an underlying type of byte, for example)
Preserving the restricted values in the face of serialization is interesting
On the other hand, such types can act polymorphically and have more information than plain enums, which can be useful.
Just to add to Jon's answer: You can always use
Enum.IsDefined(typeof(MyCode), value)
To check if the provided value exists in the enums definition.
In many ways, Enums are implemented as syntactic sugar in .NET languages. To quote,
The enum keyword is used to declare an enumeration, a distinct type consisting of a set of named constants called the enumerator list.
In other words, the values of the enum are fields like any other, not an integral selection of values. There is nothing stopping you from casting invalid values into an enum. The most you can do to forcibly ensure the valid content of an enum is using the Enum.IsDefined static method (though you may want to define extension methods if this takes your fancy).
Nevertheless, the purpose of enums isn't to validate user input, so they don't have to be as strict as that. The purpose of enums is to tie a name to a numeric value, and to easily display a list of possible combinations of this sort. And don't forget that their loose construction allows things like Day.Saturday | Day.Friday or more complex couplings. They're still very useful.

Is there a word that encompasses "classes" and "structs"?

Classes and structs in C# share several characteristics:
they can be instantiated (absent restrictions to the contrary, as with abstract and static classes)
they can contain method and property implementations
the type's author defines the type's instance fields
We often use "class" and "struct" to distinguish between "reference type" and "value type", but sometimes it's useful to consider both types of types. Furthermore, "reference type" also includes interfaces and delegates, which are not classes. So "class" doesn't mean any reference type, it means "a reference _(fill in the blank)_".
For example, if reference and value type declarations were like this:
public sealed class ref String { }
public class val Int32 { }
instead of like this:
public sealed class String { }
public struct Int32 { }
then the word "class" could be used to denote the concept.
The best answer I've come up with here is "concrete type", but that would be confusing, since it could also refer to the non-abstract subclass of an abstract class.
Any suggestions?
EDIT
To clarify, I'm not seeking a word that can collectively describe instances of classes and structs. I'm trying to describe class types and struct types.
In other words, if "class" denotes a set that includes System.String, System.FileInfo, etc., and "struct" denotes a set that includes System.Int32, System.Collections.Generic.List<T>.Enumerator, etc., then I'm looking for the word that denotes the union of those sets.
EDIT 2
(In reaction to Jordão's answer) Another way to answer this question would be to complete the following sentence: "All C# method implementations must be declared as members of a _(fill in the blank)_".
I normally use the term "type" to refer to any of those elements: class, struct and even interfaces and enums.
I never really felt the need to talk about classes and structs exclusively, I would probably just say "class", and then differentiate them as needed.
The term type in C# can refer to any of:
Reference Types
object, dynamic and string
Class types
Interface types
Delegate types
Constructed class/interface/delegate types (e.g. List<string>)
Array types
Value types
Struct types
Enumeration types
Simple types (integral types, floating point types, decimal, and bool)
Nullable types
Pointer types
All of these are terms from the C# specification.
class, interface, delegate, struct and enum types are also called type declarations (or: user-definable types).
Depending on your point of view, you might also consider type parameters and void to be types.
However, there isn't any special term for "classes or structs". In the language of the C# specification, one would say:
All C# method implementations must be declared as members of a class or struct declaration.
I realize this question has a selected answer, but I believe I can offer a fresh insight that will still be helpful:
I think the word you are looking for may be Model. This term is used to mean several different things in CS, but the wikipedia article for mathematical model describes my intension.
In this context, a model is a description of a system in some meta language. A system can be fully expressed in terms of its three parts: structure; behavior; and, interconnectivity. Both .NET classes and .NET structs are compatible with this definition. Interfaces are not, because the behavior is not defined. You can only indicate the structure of method calls and member declarations and the type contracts for operations (interconnectivity). Enums may or may not be compatible with this definition, but as most frequently used are not, because they typically do not express behavior. The exceptions are enums for which bitwise operations are sufficient representations of meaningful set operations. With this precondition, I think its fair to classify an enum along with classes and structs.
As a side note, both interfaces and standard enums could be considered as systems by themselves, if extension methods were interpreted as intrinsic to the types they extend. However, neither the compiler nor I would consider extension methods to be intrinsic to the type of the first operand. A more accurate interpretation would be to consider both the enum/interface and the extension method as necessary components of a system. The difference between these component types that are extended and a class/struct/special-case enum is that the class/struct/special-case enum is a system in-itself, and therefore a subsystem of its containing system, whereas the component type is a component but not a system in itself.
It is probably worthwhile to clarify that, under this interpretation, the term model is analogous to a type, whereas the term system is analogous to an instance. A system could also apply to a larger composite, such as an assembly, but that is not what the question was about.
The statement "All C# method implementations must be declared as members of a model" seems to work. It also does not logically entail that "all models can contain custom method implementations", so we are safe in the special-case of set-theoretic enums. It would also work in the case where the modeled system is the composition of static extension method implementations and interfaces.
 
I find this to be a pseudo discussion. Point #3 can be said about enums and interfaces too, and the point about subclasses of abstract classes not fitting into the mix, I simply don't get. I think your own suggestion of "concrete types" is ok, but maybe you just want to talk about them as classes and structs, oh wait, but with the exception of subclasses of abstract classes and classes that implement interfaces. The reason that there is no term for what you are looking for might be that it is not a very useful concept in its own right.
EDIT:
All C# method implementations must be declared as members of a class or struct.
It should be Microsoft term. The origin of these notions is C++, where structs are just classes with all members being public. So, Microsoft cooked some new judging here, mixing some of C, C++ and Java. So they should invent also a terms.
Microsoft denotes them all as "types" which can be "value", "reference" and "pointer": http://msdn.microsoft.com/en-us/library/3ewxz6et(v=vs.100).aspx
But these notions do not gather only structs and classes.
So, if invent some custom term, we may take one from Pascal language, for example, where it is "record". Or some other terms can be coined from here: http://en.wikipedia.org/wiki/Object_composition
Both classes and structs are types which define objects. They are building blocks within an object oriented programming language. You can model both of them using UML or some other high-level object oriented modelling language. The choice between one or the other is an implementation detail.

Why do unboxed types have methods?

Why can you do things like
int i = 10;
i.ToString();
'c'.Equals('d');
1.ToString();
true.GetType();
in C#? Those things right there are either primitive, literal, unboxed, or any combination of those things; so why do they have methods? They are not objects and so should not have methods. Is this syntax sugar for something else? If so, what? I can understand having functions that do these things, for example:
string ToString(int number)
{
// Do mad code
return newString;
}
but in that case you would call it as a function, not a method:
string ranch = ToString(1);
What's going on here?
edit:
Just realised C# isn't a java clone anymore and the rules are totally different. oops :P
They act like that because the spec says so (and it's pretty nice) :
1.28 Value types
A value type is either a struct type or an enumeration type. C# provides a set of predefined struct types called the simple types.
The simple types are identified through reserved words.
...
1.28.4 Simple types
C# provides a set of predefined struct types called the simple types.
The simple types are identified through reserved words, but these
reserved words are simply aliases for predefined struct types in the
System namespace, as described in the table below.
...
Because a simple type aliases a struct type, every simple type has
members. For example, int has the members declared in System.Int32 and
the members inherited from System.Object, and the following statements
are permitted:
int i = int.MaxValue; // System.Int32.MaxValue constant
string s = i.ToString(); // System.Int32.ToString() instance method
string t = 123.ToString(); // System.Int32.ToString() instance method
The simple types differ from other struct types in that they permit
certain additional operations:
Most simple types permit values to be created by writing literals
(§1.16.4). For example, 123 is a literal of type int and 'a' is a
literal of type char. C# makes no provision for literals of struct
types in general, and nondefault values of other struct types are
ultimately always created through instance constructors of those
struct types.
As the spec explains simple types have some super powers like the ability to be const, a special literal syntax that could be used instead of new, and the capacity to be computed at compilation time (2+2 is actually written as 4 in the final MSIL stream)
But methods (as well as operators) aren't a special super powers and all structs could have them.
The specification (for C# 4.0, my copy paste is from an earlier version) could be downloaded from the microsoft website : C# Language Specification 4.0
Eric Lippert's recent article Inheritance and Representation explains.(Spoiler: You are confusing inheritance and representation.)
Not sure why you claim that the integer i, the character 'c' and the integer 1 are not objects. They are.
In C# all primitive types are actually structures.
So that you can use them!
It's convenient to be able to do so, so you can.
Now, in order to do so, primitives can be treated as structs. E.g. a 32-bit integer can be processed as a 32-bit integer, but it can also be processed as public struct Int32 : IComparable, IFormattable, IConvertible, IComparable<int>, IEquatable<int>. We mostly get the best of both worlds.

When do I use struct instead of having class in c#? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
When should I use a struct instead of a class?
By Venkat K in the C# .NET forum.
29-Apr-09 07:38 AM
The only difference between "class" and "struct" is that a struct defaults to having public members (both data members and function members) and a struct defaults to public inheritance, whereas a class defaults to private members and private inheritance. That is the only difference. This difference can be circumvented by explicitly specifying "public", private", or "protected" so a struct can be made to act like a class in ever way and vice versa.by convention, most programmer's use "struct" for data types that have no member functions and that do not use inheritance. They use "class" for data types with member functions and inheritance. However, this is not necessary or even universallly acepted.
*(Can this be true)
That statement is entirely false when it comes to C#. I believe it may well be true for C++, but in C# the difference is between a value type (structs) and a reference type (classes).
It's not the only difference. Structs are value types and classes are reference types. Look it up on Google to find out more about the differences, which are too many to list in the minute I have right now.
Unless, as #BrokenGlass points out it's C++.
The statement you quote would be correct for C++, but not for C#. Here's an excerpt of what the C# Language Specification has to say about structs:
Like classes, structs are data structures that can contain data members and function members, but unlike classes, structs are value types and do not require heap allocation. A variable of a struct type directly stores the data of the struct, whereas a variable of a class type stores a reference to a dynamically allocated object. Struct types do not support user-specified inheritance, and all struct types implicitly inherit from type object.
Structs are particularly useful for small data structures that have value semantics. Complex numbers, points in a coordinate system, or key-value pairs in a dictionary are all good examples of structs. The use of structs rather than classes for small data structures can make a large difference in the number of memory allocations an application performs.

Why do C# and VB have Generics? What benefit do they provide? Generics, FTW

From Wikipedia:
Generic programming is a style of
computer programming in which
algorithms are written in terms of
to-be-specified-later types that are
then instantiated when needed for
specific types provided as parameters
and was pioneered by Ada which
appeared in 1983. This approach
permits writing common functions or
types that differ only in the set of
types on which they operate when used,
thus reducing duplication.
Generics provide the ability to define types that are specified later. You don't have to cast items to a type to use them because they are already typed.
Why does C# and VB have Generics? What benefit do they provide? What benefits do you find using them?
What other languages also have generics?
C# and VB have generics to take advantage of generics support in the underlying CLR (or is the other way around?). They allow you to write code ina statically-typed language that can apply to more than one kind of type without rewriting the code for each type you use them for (the runtime will do that for you) or otherwise using System.Object and casting everywhere (like we had to do with ArrayList).
Did you read the article?
These languages also have generics:
C++ (via templates)
Ada (via templates)
Eiffel
D (via templates)
Haskell
Java
Personally, I think they allows to save a lot of time. I'm still using .NET Framework 1.1 and every time you want a specific collection, you need to create a strongly typed collection by implementing CollectionBase. With Generics, you just need to declare your collection like that List<MyObject> and it's done.
Consider these method signatures:
//Old and busted
public abstract class Enum
{
public static object Parse(Type enumType, string value);
}
//To call it:
MyEnum x = (MyEnum) Enum.Parse(typeof(MyEnum), someString);
//New and groovy
public abstract class Enum
{
public static T Parse<T>(string value);
}
//To call it:
MyEnum x = Enum.Parse<MyEnum>(someString);
Look ma: No runtime type manipulation.
From MSDN:
Generics provide the solution to a
limitation in earlier versions of the
common language runtime and the C#
language in which generalization is
accomplished by casting types to and
from the universal base type Object.
By creating a generic class, you can
create a collection that is type-safe
at compile-time.
Read the rest of that article to see some examples of how Generics can improve the readability and performance of your code.
Probably the most common use for them is having strongly typed ArrayLists. In .NET 1.1, you'd either have to cast everything from object to your desired Type, or use something like CodeSmith to generate a strongly typed ArrayList.
Additionally, they help decrease boxing. Again, in .NET 1.x, if you tried to use an ArrayList with a Value Type, you'd end up boxing and unboxing the objects all over the place. Generics avoid that by letting you define the Type, whether Reference or Value.
There are other handy uses for them too, event handlers, LINQ queries, etc.
Generics in .NET are excellent for object collections. You can define your object type however you want and be able to have, say, a List without writing any code for that, and have access to all the efficient functionality of the .NET List generic collection while being type-safe to T. It's great stuff.
Generics are build on the concept of templates in c++ if you are familiar with them.
Its a way to implement an algorithm or data structure but delaying the actual type it is used on.
List can then be assigned with any type of your choice int, string and even custom types the type is assigned on construction of the list. But you will be able to use the list operations add remove etc.
You can really save a lot of coding effort by getting used to generics. And you don't have to box and unbox between types.
Java have generics as well. They are called wildcards.
Generics in .net, like inheritence and extension methods, allows for reduction of code duplication. Let me explain by way of refactoring.
If all classes with a common ancestor have a common method, place the common method in the classes' common ancestor (inheritence).
If some classes have a common method that uses a public contract to achieve some result, make the common method into an extension method on that public contract.
If some several methods or classes have the same code that differs only by the types acted upon (especially where the details of the type are not relevant to the operation of the method), collect those methods or classes into a generic.
They increase performance for collections using value types, since no boxing/unboxing will be required. They're a lot cleaner to use since you won't have to cast an object (for example using ArrayList) to the desired type - and likewise they help enforce type safety.
Biggest advantage of generics over non generic types in C# (not Java, Java is a different story) is that they are much faster. The JIT generates the best machine code it can come up with for a given type. List<int> is actually a list of ints and not integer objects wrapping an int. This makes generic types awesomely fast and also type safe which can help you detect an awesome lot of errors at compile time :)
The common example is collections. e.g. a set of type T, as an Add(T) method and a T get() method. Same code, different type safe collections.
C++, D, Ada and others have templates, a superset of generics that do it a little different bug get the same end result (and then some).
IIRC Java has generics, but I don't do Java.
The easiest way to explain it is to give an example. Say you want two hashtables, one that maps objects of type string to type int and one that maps objects of type string to type double. You could define Hashtable and then use the K and V types. Without generics, you'd have to use the 'object' type which, in addition to having to be cast to be meaningful, gives up typesafety. Just instantiate Hashtable and Hashtable and you've got your hash tables with proper typechecking and all.
Java also has generics. C++ has templates.
Dynamic languages like Perl and Javascript don't have the same type restrictions so they get mostly the same benefits with less work.
In objective-C you can use protocols to achieve the aims of generics. Since the language is weakly typed however, it's generally not as much of a concern as when you are fighting the type system to use one code path for many types.
Personally I am a huge fan of generics because of all of the code I don't have to write.
What is Inversion of Control?

Categories