See below enum contains two members: Test and Production
public enum OTA_HotelInvCountNotifRQTarget
{
Test,
Production,
}
I'm looking for the way to add and use Null value in above enum from code like :
inv.Target = OTA_HotelInvCountNotifRQTarget.Null; // Not allowed
Update:
I do not want to add extra NULL in above enum, I want to make this dynamic because the above enum is auto generated. and should be remain same.
Is there a way to achieve this in a method itself i.e without creating any Class or adding extra Enum value in enum?
like : inv.Target = OTA_HotelInvCountNotifRQTarget.Null;
How can I do this?
The underlining values of an enum are int which can't be assigned to null.
If you still want to do so:
Add Null as an option to the enum:
public enum OTA_HotelInvCountNotifRQTarget
{
Null,
Test,
Production
}
Have your target a Nullable type:
Nullable<OTA_HotelInvCountNotifRQTarget> t = null;
//Or in a cleaner way:
OTA_HotelInvCountNotifRQTarget? t = null;
//And in your class:
public class YourType
{
public OTA_HotelInvCountNotifRQTarget? Target { get; set; }
}
public enum OTA_HotelInvCountNotifRQTarget
{
Null,
Test,
Production
}
also answewred here
How to set enum to null
Enum is enum. It value type and you can use
Nullable<OTA_HotelInvCountNotifRQTarget> or OTA_HotelInvCountNotifRQTarget? for represent "not set statement"
but if you still want user null as enum value try
public enum OTA_HotelInvCountNotifRQTarget
{
Null,
Test,
Production
}
Or using the "?" Operator for the variable:
public OTA_HotelInvCountNotifRQTarget? Target;
You have to change the assignment to:
inv.Target = null;
Related
I have an enum on helper library in my solution.
For example
public enum MyEnum
{
First,
Second
}
I want to use MyEnum in a few another project. I want to decorate this enum in each project with own attribute like this:
public enum MyEnum
{
[MyAttribute(param)]
First,
[MyAttribute(param2)]
Second
}
How to decorate enum from another library with own local attribute?
You can't do what you've described - the best you can do is to create a new Enum that uses the same set of values. You will then need to cast to the "real" enum whenever you use it.
You could use T4 templates or similar to generate the attributed enum for you - it would be much safer that way as it would be very easy to map the wrong values, making for some very subtle bugs!
Linqpad Query
enum PrimaryColor
{
Red,
Blue,
Green
}
enum AttributedPrimaryColor
{
[MyAttribute]
Red = PrimaryColor.Red,
[MyAttribute]
Blue = PrimaryColor.Blue,
[MyAttribute]
Green = PrimaryColor.Green
}
static void PrintColor(PrimaryColor color)
{
Console.WriteLine(color);
}
void Main()
{
// We have to perform a cast to PrimaryColor here.
// As they both have the same base type (int in this case)
// this cast will be fine.
PrintColor((PrimaryColor)AttributedPrimaryColor.Red);
}
Attributes are compile-time additions (metadata) to code. You can not modify them when using the compiled code assembly.
(Or perhaps you could if you are a diehard low-level IL wizard, but I certainly am not...)
If your enum values require modification or parameters at various places, then you should consider other solutions, e.g. a Dictionary or even a Database Table.
E.g. using a Dictionary:
var values = new Dictionary<MyEnum, int>()
{
{ MyEnum.First, 25 },
{ MyEnum.Second, 42 }
};
var valueForSecond = values[MyEnum.Second]; // returns 42
You can do something like this, but it will be tedious.
The idea is to use your project settings to allow the change when you import the enum in a new project.
First, you will need 2 attributes:
// This one is to indicate the format of the keys in your settings
public class EnumAttribute : Attribute
{
public EnumAttribute(string key)
{
Key = key;
}
public string Key { get; }
}
// This one is to give an id to your enum field
[AttributeUsage(AttributeTargets.Field)]
public class EnumValueAttribute : Attribute
{
public EnumValueAttribute(int id)
{
Id = id;
}
public int Id { get; }
}
Then, this method:
// This method will get your attribute value from your enum value
public object GetEnumAttributeValue<TEnum>(TEnum value)
{
var enumAttribute = (EnumAttribute)typeof(TEnum)
.GetCustomAttributes(typeof(EnumAttribute), false)
.First();
var valueAttribute = (EnumValueAttribute)typeof(TEnum).GetMember(value.ToString())
.First()
.GetCustomAttributes(typeof(EnumValueAttribute), false)
.First();
return Settings.Default[String.Format(enumAttribute.Key, valueAttribute.Id)];
}
I did not check if the type is correct, not even if it finds any attributes. You will have to do it, otherwise you will get an exception if you don't provide the right type.
Now, your enum will look like that:
[Enum("Key{0}")]
public enum MyEnum
{
[EnumValue(0)] First,
[EnumValue(1)] Second
}
Finally, in your project settings, you will have to add as many lines as the number of members in your enum.
You will have to name each line with the same pattern as the parameter given to EnumAttribute. Here, it's "Key{0}", so:
Key0: Your first value
Key1: Your second value
etc...
Like this, you only have to change your settings values (NOT THE KEY) to import your enum and change your attributes to a project to another.
Usage:
/*Wherever you put your method*/.GetEnumAttributeValue(MyEnum.First);
It will return you "Your first value".
I have a panel with a dropdown; which I use to set a field in my project.
public class projectclass
{
public enum mainpriority
{
basic,
urgent,
critical
};
public mainpriority _priorityfield { get; set;}
}
The project class use an enum for this field, so to populate the dropdown I do this, to populate it:
mydropdown.options.Clear();
foreach (projectclass._priorityfield priority in projectclass._priorityfield.GetValues(typeof(projectclass._priorityfield)))
{
mydropdown.options.Add( new Dropdown.OptionData() {text = priority.ToString()});
}
This allow me to display the field in the dropbox, for each instance of the projectclass.
All is good in this direction, but if I want to do the opposite (change the value in the dropdown, and change the class field accordingly), I can't make it work.
The main issue is that I try to assign to the class, the value as int (which is what I get back from the dropdown.value() method), but VS tell me that it is not possible to set a _priorityfield type with an int type.
Isn't the enum, equivalent to 0,1,2.....n; so you can either use "basic" or 0 as value?
This is what I do to set the class instance value, from the dropdown, using the onValueChanged delegate
private void UpdatePriority(Dropdown priority)
{
int tempvalue = priority.value;
projectclass_instance1._priorityfield = tempvalue;
}
I assumed that I can pass an int, but VS says that is not possible. I could map each value of the dropdown to an entry in the enum, but I am not sure that it is actually the best solution.
Thanks to Ehsan for the solution.
The error is because I need to cast the int value as enum type, so the value will be correctly recognized.
I have this line in C#, where incoming.icon is a property of a custom model, and dataItem.Icon is the property of a custom entity.
dataItem.Icon = incoming.icon;
The compiler complains because incoming.icon is nullable but dataItem.Icon isn't. Here is the dataItem 'Icon' property definition in the entity:
public Guid Icon {
get {
return ValidationHelper.GetGuid(GetValue("Icon"), Guid.Empty);
}
set {
SetValue("Icon", value);
}
}
How do I make this property nullable in order to fix the error?
Like this:
public Guid? Icon
{
get
{
return (Guid?)ValidationHelper.GetGuid(GetValue("Icon"), Guid.Empty);
}
set
{
SetValue("Icon", value.GetValueOrDefault());
}
}
Nullable is the struct that you're looking for.
public Nullable<Guid> Icon
This can be written in shorthand like so:
public Guid? Icon
If your design is that you don't want null values being set on dataItem.icon, then you might want to check incoming.icon and only get it's value if it exists instead. Like this:
if (incoming.icon.HasValue)
dataItem.Icon = incoming.icon.Value;
I have a program where I use a class store settings. I need it to use set and get functions to change and store settings. I have tried this, and I don't get it to work. Can anyone help me with this one?
private enum _Difficulty { Easy, Normal, Hard };
public void SetDifficulty(Difficulty)
{
_Difficulty = Difficulty;
}
public enum GetDifficulty()
{
return _Difficulty;
}
Is there no way to use enums in a class with get and set?
I also need this with bool and int.
There are several things wrong here:
Your enum is private, but your methods are public. Therefore you can't make your methods return type be the enum type, or have parameters with that type
Your SetDifficulty method has a parameter of just Difficulty - is that meant to be the parameter name or the type?
Your SetDifficulty method is trying to set the type rather than a field
Your GetDifficulty method is trying to use enum as a return type, and is then returning a type rather than a field
Basically, you seem to be confused about what your enum declaration is declaring - it's not declaring a field, it's declaring a type (and specifying what the named values of that type are).
I suspect you want:
// Try not to use nested types unless there's a clear benefit.
public enum Difficulty { Easy, Normal, Hard }
public class Foo
{
// Declares a property of *type* Difficulty, and with a *name* of Difficulty
public Difficulty Difficulty { get; set; }
}
You can use get/set methods if you really want to make your code look like Java instead of C#:
public enum Difficulty { Easy, Normal, Hard }
public class Foo
{
private Difficulty difficulty;
public void SetDifficulty(Difficulty value)
{
difficulty = value;
}
public Difficulty GetDifficulty()
{
return difficulty;
}
}
Once you specify an enum using the enum keyword, that enum acts as a type, like a class or struct would.
Here's how you'd implement a property with a custom enum:
public enum _Difficulty { Easy, Normal, Hard };
public _Difficulty Difficulty { get; set; }
You code tries to assign Difficulty a value, when in fact Difficulty is the name of the enum type. I would encourage use of getters and setters as properties instead:
public enum Difficulty { Easy, Normal, Hard };
private Difficulty _difficulty;
public Difficulty CurrentDifficulty
{
get { return _difficulty; }
set { _difficulty = value; }
}
This way you can add additional code in the setter for special conditions. To use it you simply do the following:
//set
CurrentDifficulty = Difficulty.Easy;
//get
Difficulty theDifficulty = CurrentDifficulty;
The enum you want to use needs to be public. You also need an instance of that enum to store the value you're setting, you're currently setting it to your enum's declaration. Then you want to use the same enum type for what your class stores and what you pass in.
public enum Difficulty { Easy, Normal, Hard };
public Difficulty { get; set; }
There are a number of issues here:
Your enum is private, so nothing will be able to call SetDifficulty to provide it with a value from that enum. Indeed, the compiler won't allow this.
The argument to SetDifficulty is just a type, it also needs a variable name. Also a compiler error.
You're trying to get/set the value of the enumeration itself, rather than a class-level variable of the type of the enumeration. This too won't compile.
It looks like you want to do this:
public enum Difficulty { Easy, Normal, Hard }
public Difficulty DifficultySetting { get; set; }
Note that I had to change the name of the property to DifficultySetting because it conflicts with the enum name. Yours used an underscore, which would also solve that problem. However I always found that underscores are for private members and if you want consuming code to use this enum then it would need to be public. Decorating a public member with things like underscores distracts from the semantics of the name itself. In any event, the semantics are up to your personal preference, so you can modify these names as you see fit.
I'm not sure you are using them correctly. This might help...
private enum Difficulty { Easy, Normal, Hard };
private Diffuculty theDifficulty;
public void SetDifficulty(difficulty d)
{
theDifficulty = difficulty;
}
public Difficulty GetDifficulty()
{
return theDifficulty;
}
An enum is a type not a variable. Something like this would work:
public enum Difficulty { Easy, Normal, Hard };
private Difficulty _Difficulty;
public void SetDifficulty(Difficulty difficulty )
{
_Difficulty = Difficulty;
}
public Difficulty GetDifficulty()
{
return _Difficulty;
}
or more succinctly as an Auto Property:
private Difficulty Difficulty {get; set;}
Note that the enum has to be public if you want it to be accessible from public methods.
public bool PrepaymentCalculating { get; set; }
So I declare a variable on one of my classes like that. I want this to default to 'null' and not false. Would I just need to make this a nullable boolean? Or is there a better way to do this?
Would I just need to make this a nullable boolean?
Yes.
Or is there a better way to do this?
No.
You can achieve this with
public bool? PrepaymentCalculating { get; set; }
try
public bool? PrepaymentCalculating { get; set; }
Here's a post on Nullable Types
public bool? PrepaymentCalculating { get; set; }
will make it nullable. Read about it here
If you want it to be null then you need to make it a nullable type.
Like everyone else said, but I thought I'd add, what's your purpose here? It's not often that I want to expose a nullable bool, since this means that everything that uses this property must account for a possible null value.
But sometimes I want to know if it's been initialized or not in a given context, and if not, then use a value from somewhere else (e.g. to cascade property values). In this case you might want to use a pattern like this:
public bool PrepaymentCalculating {
get {
if (_PrepaymentCalculating != null ) {
return (bool)_PrepaymentCalculating;
} else {
return somethingElse; // bool
}
}
set {
_PrepaymentCalculating = value;
}
} protected bool? _PrepaymentCalculating =null;
bool can't be null. The default is probably false (but don't quote me on that).
If you want it to be null, then yes you have to declare it as nullable.