enum in constructor

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I want to use an enum field in a constructor.

For example:

class Student
{
private string name;
private enum university {.....};
private byte course;
......

public Student ( string name, enum university)
{
.........

}

I'm fairly new to programming so any sample code would be most appreciated.



}
 
Hi Koljewa,

what do you mean by "enum field". A field is a variable (on class/struct
level).
You're defining an enum, what is a type, not a field. In this case a nested
type, because it is defined in another type.
To use this enum for a parameter in a public constructor, (or public
method), itself has to be public.
That's very usefull, because the caller has to know the type, to put a value
of that enum to the constructor.
Also you should consider not to define the enum as nested type. You also can
define enums at namespace level.
 
??????,

This won't work. The enumeration is defined as private, and has no
scope outside of the class that it is defined in. Because the constructor
is public, you can't expose a private type to the class as a parameter.
Instead, you have to declare the enumeration as public, like so:

class Student
{
private string name;
public enum university {.....};

Also, you might want to consider declaring your enumeration outside of
your class. It's more of a design issue. The decision to do so would
depend on what the enumeration represents. If the enumeration is specific
to that class, then its fine where it is, but if it is really something that
is not specific to the class, you should define it outside of the class.

Hope this helps.
 
Колева said:
I want to use an enum field in a constructor.

For example:

class Student
{
private string name;
private enum university {.....};
private byte course;
......

public Student ( string name, enum university)
{
.........

}

I'm fairly new to programming so any sample code would be most appreciated.

You probably want something like this:

enum University {
....
}

class Student
{
private string name;
private University uni;
private byte course;
...
public Student(string name, University uni){
...
}
}

Alun Harford
 
Thank you very much! :)

Alun Harford said:
You probably want something like this:

enum University {
....
}

class Student
{
private string name;
private University uni;
private byte course;
...
public Student(string name, University uni){
...
}
}

Alun Harford
 
Back
Top