www.pickatutorial.com Computer Tutorials
Top eBooks: C/C++ | C# | Android | Mathematics | Database | Cloud | Graphics | Networking | Oracle | Hardware | AI
Top Tutorials: C/C++ | C#.NET | PHP MySQL | Java | Java Script | jQuery | HTML | xHTML | HTML5 | VB Script| CSS
Lessons C# Structs and Enums Bookmark and Share
Tutorial Home
Lesson 1
Lesson 2
Lesson 3
Lesson 4
Lesson 5
Lesson 6
Lesson 7
Lesson 8
Lesson 9
Lesson 10
Lesson 11
Lesson 12
Lesson 13
Lesson 14
Lesson 15
Lesson 16
Lesson 17
Lesson 18
Lesson 19
Lesson 20
Lesson 21
Lesson 22
Lesson 23
Unlike C++ Java did not have structs which have been brought back by C#. However, as compared to C++, they are significantly different in C#. In C++ a struct is exactly like a class, except that the default inheritance and default access are public rather than private. In C# structs are very different from classes. Structs in C# are designed to encapsulate lightweight objects. They are value types unlike classes which are reference types. Like ordinaly primitive datatypes, structs are passed by value when calling or invoking methods. They are sealed, which means they cannot be derived from or have any base class other than System.ValueType, which is derived from Object. Structs cannot declare a default (parameterless) constructor.

you can declare a struct as under:

struct MyStruct {
//code goes here

C# also brought back enumerations which were discarded by Java designers. However, they are slightly different from C++.

An enumeration is a special kind of value type, limited to a restricted and unchangeable set of numerical values. By default, these numerical values are integers, but they can also be of types long, byte, etc. (any numerical value except char). By default the first item in an enumeration has the integer value 0 and every subsequest item has a value of 1 + the value of the previous item. Consider the following example:
public enum DAYS {
In the above code the integer value associated with Monday is 0, Tuesday equals 1 and son on.

In C# enumerations are type-safe i.e. the compiler will do its best to stop you from assigning illegal values to enumeration typed variables. For instance, the following code does not compile:

int i = DAYS.Monday;
DAYS d = i;

In order to get the above code to compile, you have to make explicit casts both ways (even converting from DAYS to int), i.e.:

int i = (int)DAYS.Monday;
DAYS d = (DAYS)i;

A useful feature of enumerations is that one can retrieve the literal as a string from the numeric constant with which it is associated. In fact, this is given by the default ToString() method, so the following expression comes out as true:

Next >>> Lesson No. 13: C# Arrays

Home - Advertise - Contact - Disclaimer - About Us
© Since 2006 pickatutorial.com -- All Rights Reserved.