call enum as argument in Method?
-
Greetings all - first time poster here, so please forgive me if I've submitted this incorrectly A user selects from a list of enum. I want that enum to be the actual name of a var. Then I'd like to use (some kind of placeholder argument in a method), to call that selected enum and evaluate the method. Here is the relevant example section:
{
public enum Fruit
{
Apple, Orange
}\[Parameter("Fruit Type")\] public Fruit FruitType { get; set; } public override void Calculate { var Apple = 5 var Orange = 1 bool MoreApples = Apple > Orange; bool FewerApples = Apple < Orange; if (FruitType == Fruit.Apple && MoreApples) { //do something } if (FruitType == Fruit.Orange && FewerApples) { //do something else }
Is there some better way to assign the enum to a var (or other way around??), and then have a Method call the chosen enum, and return the actual bool data in order to see if the IF is satisfied? Perhaps this is an array thing? I was hoping to use something like: FruitType == Fruit.XXX, with XXX pulling selected enum. Thank you all for helping the C# newbie -
I am going to guess that what you are after is something like this: using a Dictionary whose Key is an Enum value, and whose Value is executable code defined in a deferred form (Func, Action, Delegate, Lambda Expression):
using System;
using System.Collections.Generic;namespace YourNameSpace
{
public enum Fruit
{
NoFruit, Apple, Orange
}public class FruitCalc { private Dictionary\> CalcFruitDict = new Dictionary\> { **// lambda notation used here** {Fruit.Apple, (int napples, int noranges) => napples > noranges ? Fruit.Apple : Fruit.NoFruit }, {Fruit.Orange, (int napples, int noranges) => napples < noranges ? Fruit.Orange : Fruit.NoFruit }, }; public Fruit Calculate(Fruit fruit, int napples, int noranges) { if (fruit == Fruit.NoFruit) { throw new InvalidOperationException("Sorry, no fruit means no fruit"); } // check integer parameters for valid range ? return CalcFruitDict\[fruit\](napples, noranges); } }
}
Usage example:
FruitCalc fcalc = new FruitCalc();
Fruit f1 = fcalc.Calculate(Fruit.Apple, 12, 4);
Fruit f2 = fcalc.Calculate(Fruit.Orange, 14, 24);Fruit f3 = fcalc.Calculate(Fruit.Apple, 2, 4);
Fruit f4 = fcalc.Calculate(Fruit.Orange, 14, 2);// force an error
Fruit f5 = fcalc.Calculate(Fruit.NoFruit, 12, 4);Note: the case where number of apples equals number of oranges is not handled here.
«One day it will have to be officially admitted that what we have christened reality is an even greater illusion than the world of dreams.» Salvador Dali
-
Quote:
I want that enum to be the actual name of a var.
Nope. You don't get to do that. The values in an enum should not be thought of as variable names at all. Expanding that a little, if you have a string variable with the name of a variable as its value, that's also wrong. It may work in interpreted languages, but it doesn't work in compiled languages. The variable names no longer exist(*). * There is, of course, an exception. The namespaces, classes, method names, variables, and other code objects/names ARE available as metadata in .NET code. You access that data through the System.Reflection classes. Using reflection in your code will WAY over-complicate your code and reduce its performance. Reflection is not a quick thing. Don't do it unless you have a very specific reason and no other options. In your example, your Calculate method should accept a parameter, FruitType. You don't appear to need the property at all. Of course, this makes assumptions that you don't show in your code nor explain in your question.
public override void Calculate(FruitType fruitType)
A method with the name Calculate also suggests it should return a value, which your code doesn't.
Asking questions is a skill CodeProject Forum Guidelines Google: C# How to debug code Seriously, go read these articles.
Dave KreskowiakDave Kreskowiak wrote:
... values in an enum should not be thought of as variable names at all ... It may work in interpreted languages, but it doesn't work in compiled languages. The variable names no longer exist(*).
Hi, Dave, I take exception to this conclusion in the limited sense that we can use Enum values as variables which function as indexes to deferred execution code, as shown in my response on this thread.
«One day it will have to be officially admitted that what we have christened reality is an even greater illusion than the world of dreams.» Salvador Dali
-
Quote:
I want that enum to be the actual name of a var.
Nope. You don't get to do that. The values in an enum should not be thought of as variable names at all. Expanding that a little, if you have a string variable with the name of a variable as its value, that's also wrong. It may work in interpreted languages, but it doesn't work in compiled languages. The variable names no longer exist(*). * There is, of course, an exception. The namespaces, classes, method names, variables, and other code objects/names ARE available as metadata in .NET code. You access that data through the System.Reflection classes. Using reflection in your code will WAY over-complicate your code and reduce its performance. Reflection is not a quick thing. Don't do it unless you have a very specific reason and no other options. In your example, your Calculate method should accept a parameter, FruitType. You don't appear to need the property at all. Of course, this makes assumptions that you don't show in your code nor explain in your question.
public override void Calculate(FruitType fruitType)
A method with the name Calculate also suggests it should return a value, which your code doesn't.
Asking questions is a skill CodeProject Forum Guidelines Google: C# How to debug code Seriously, go read these articles.
Dave KreskowiakDave -- Thank you VERY much for the explanation- I am such beginner, I am having trouble knowing what I yet don't know (which is mostly everything). 1) a user selectable list of things (enums - or some other way?) 2) var(s) initialized that calculate something 3) an IF that wants to evaluate whether some var && some other var are true), and if so, do something. as it is now, I have to hard code all possibilities for each if (of each selected enums) using the vars directly. What I'd like is a way to have the user selected choice populate the iF with the appropriate var - that would alleviate hard coding each and every possibility. Am I even phrasing the question properly? probably not -- And if not, can you point me to an area I should study as to be better informed about syntax and possibilities? If I am way off, many apologies... Thanks so much again for your help-
-
Dave Kreskowiak wrote:
... values in an enum should not be thought of as variable names at all ... It may work in interpreted languages, but it doesn't work in compiled languages. The variable names no longer exist(*).
Hi, Dave, I take exception to this conclusion in the limited sense that we can use Enum values as variables which function as indexes to deferred execution code, as shown in my response on this thread.
«One day it will have to be officially admitted that what we have christened reality is an even greater illusion than the world of dreams.» Salvador Dali
While you are correct, I limited my answer to the context of "beginner". Yeah, it's a little white lie, for the sake of simplicity and learning the basics first.
Asking questions is a skill CodeProject Forum Guidelines Google: C# How to debug code Seriously, go read these articles.
Dave Kreskowiak -
Greetings all - first time poster here, so please forgive me if I've submitted this incorrectly A user selects from a list of enum. I want that enum to be the actual name of a var. Then I'd like to use (some kind of placeholder argument in a method), to call that selected enum and evaluate the method. Here is the relevant example section:
{
public enum Fruit
{
Apple, Orange
}\[Parameter("Fruit Type")\] public Fruit FruitType { get; set; } public override void Calculate { var Apple = 5 var Orange = 1 bool MoreApples = Apple > Orange; bool FewerApples = Apple < Orange; if (FruitType == Fruit.Apple && MoreApples) { //do something } if (FruitType == Fruit.Orange && FewerApples) { //do something else }
Is there some better way to assign the enum to a var (or other way around??), and then have a Method call the chosen enum, and return the actual bool data in order to see if the IF is satisfied? Perhaps this is an array thing? I was hoping to use something like: FruitType == Fruit.XXX, with XXX pulling selected enum. Thank you all for helping the C# newbie -
This is a simpler version using a 'switch statement:
public Fruit Calculate2(Fruit fruit, int napples, int noranges)
{
switch (fruit)
{
case Fruit.Apple:
return napples > noranges ? Fruit.Apple : Fruit.NoFruit;
case Fruit.Orange:
return napples < noranges ? Fruit.Orange : Fruit.NoFruit;
default:
throw new InvalidOperationException("Sorry, no fruit means no fruit");
}
}«One day it will have to be officially admitted that what we have christened reality is an even greater illusion than the world of dreams.» Salvador Dali
-
Dave -- Thank you VERY much for the explanation- I am such beginner, I am having trouble knowing what I yet don't know (which is mostly everything). 1) a user selectable list of things (enums - or some other way?) 2) var(s) initialized that calculate something 3) an IF that wants to evaluate whether some var && some other var are true), and if so, do something. as it is now, I have to hard code all possibilities for each if (of each selected enums) using the vars directly. What I'd like is a way to have the user selected choice populate the iF with the appropriate var - that would alleviate hard coding each and every possibility. Am I even phrasing the question properly? probably not -- And if not, can you point me to an area I should study as to be better informed about syntax and possibilities? If I am way off, many apologies... Thanks so much again for your help-
See if the code using a 'switch statement in my second reply seems useful.
«One day it will have to be officially admitted that what we have christened reality is an even greater illusion than the world of dreams.» Salvador Dali
-
While you are correct, I limited my answer to the context of "beginner". Yeah, it's a little white lie, for the sake of simplicity and learning the basics first.
Asking questions is a skill CodeProject Forum Guidelines Google: C# How to debug code Seriously, go read these articles.
Dave KreskowiakDave Kreskowiak wrote:
context of "beginner"
good point, Dave ! I've added a second reply here showing use of a 'switch statement ... hope it be useful to the OP.
«One day it will have to be officially admitted that what we have christened reality is an even greater illusion than the world of dreams.» Salvador Dali
-
Greetings all - first time poster here, so please forgive me if I've submitted this incorrectly A user selects from a list of enum. I want that enum to be the actual name of a var. Then I'd like to use (some kind of placeholder argument in a method), to call that selected enum and evaluate the method. Here is the relevant example section:
{
public enum Fruit
{
Apple, Orange
}\[Parameter("Fruit Type")\] public Fruit FruitType { get; set; } public override void Calculate { var Apple = 5 var Orange = 1 bool MoreApples = Apple > Orange; bool FewerApples = Apple < Orange; if (FruitType == Fruit.Apple && MoreApples) { //do something } if (FruitType == Fruit.Orange && FewerApples) { //do something else }
Is there some better way to assign the enum to a var (or other way around??), and then have a Method call the chosen enum, and return the actual bool data in order to see if the IF is satisfied? Perhaps this is an array thing? I was hoping to use something like: FruitType == Fruit.XXX, with XXX pulling selected enum. Thank you all for helping the C# newbie -
To add to what the others say: never rely on variable names in your code in the way you seem to be describing. While (as Dave says) that can be done, it does have a significant drawback in the real world. Namely: it may fail spectacularly in production. It's quite common to use obfuscation to "protect" source code from re-generation from the EXE file - which is certainly possible in C# thanks to the metadata that Dave mentioned. But obfuscation throws away that metadata and substitutes a randomised version to make it a lot harder to read. And there go your enum names, your variables, even your method names (unless they are directly exposed outside the assembly). Generally, if you are trying to do that, you are over complicating your software, and probably should sit down and think very carefully if that is the way you need to go.
Sent from my Amstrad PC 1640 Never throw anything away, Griff Bad command or file name. Bad, bad command! Sit! Stay! Staaaay... AntiTwitter: @DalekDave is now a follower!
-
Greetings all - first time poster here, so please forgive me if I've submitted this incorrectly A user selects from a list of enum. I want that enum to be the actual name of a var. Then I'd like to use (some kind of placeholder argument in a method), to call that selected enum and evaluate the method. Here is the relevant example section:
{
public enum Fruit
{
Apple, Orange
}\[Parameter("Fruit Type")\] public Fruit FruitType { get; set; } public override void Calculate { var Apple = 5 var Orange = 1 bool MoreApples = Apple > Orange; bool FewerApples = Apple < Orange; if (FruitType == Fruit.Apple && MoreApples) { //do something } if (FruitType == Fruit.Orange && FewerApples) { //do something else }
Is there some better way to assign the enum to a var (or other way around??), and then have a Method call the chosen enum, and return the actual bool data in order to see if the IF is satisfied? Perhaps this is an array thing? I was hoping to use something like: FruitType == Fruit.XXX, with XXX pulling selected enum. Thank you all for helping the C# newbie -
You're struggling because you're missing some key language components that are very useful for what your are trying to do. Look at Action<> and Func<>; then maybe delegates; in that order. They can be passed around and added to collections and treated like a variable. "Pointers to methods / functions". [Action Delegate (System) | Microsoft Docs](https://docs.microsoft.com/en-us/dotnet/api/system.action?view=netframework-4.8) [C# Delegates, Actions, Funcs, Lambdas–Keeping it super simple – Bruno Terkaly – Developer Evangelist – bterkaly@microsoft.com](https://blogs.msdn.microsoft.com/brunoterkaly/2012/03/02/c-delegates-actions-funcs-lambdaskeeping-it-super-simple/)
The Master said, 'Am I indeed possessed of knowledge? I am not knowing. But if a mean person, who appears quite empty-like, ask anything of me, I set it forth from one end to the other, and exhaust it.' ― Confucian Analects
-
Greetings all - first time poster here, so please forgive me if I've submitted this incorrectly A user selects from a list of enum. I want that enum to be the actual name of a var. Then I'd like to use (some kind of placeholder argument in a method), to call that selected enum and evaluate the method. Here is the relevant example section:
{
public enum Fruit
{
Apple, Orange
}\[Parameter("Fruit Type")\] public Fruit FruitType { get; set; } public override void Calculate { var Apple = 5 var Orange = 1 bool MoreApples = Apple > Orange; bool FewerApples = Apple < Orange; if (FruitType == Fruit.Apple && MoreApples) { //do something } if (FruitType == Fruit.Orange && FewerApples) { //do something else }
Is there some better way to assign the enum to a var (or other way around??), and then have a Method call the chosen enum, and return the actual bool data in order to see if the IF is satisfied? Perhaps this is an array thing? I was hoping to use something like: FruitType == Fruit.XXX, with XXX pulling selected enum. Thank you all for helping the C# newbie -
In your UI, you have an event handler for the dropdown list, so we'll start from that perspective. ```csharp public void DropDownSelectChanged(object sender, EventArgs args) { // assuming the sender is the drop down var ddl = sender as DropDown; // whatever the actual control is in your GUI Calculate(ddl.SelectedItem); } ``` The Calculate method will then call the appropriate Action to react to the state of the application. ```csharp // These get set in your constructor. public Action MoreApplesAction {get; set;} public Action FewerApplesAction {get; set;} public void Caclulate(Fruit selectedFruit) { // Of course, these should be properties somewhere var Apple = 5 var Orange = 1 // It's OK to create guards like this to // enhance readability, but don't be surprised // when someone objects because of the memory // allocation. var MoreApples = Apple > Orange; var FewerApples = Apple < Orange; switch(selectedFruit) { case Apple: if(MoreApplies) MoreApplesAction?.Invoke(); break; case Orange: if(FewerApples) FewerApplesAction?.Invoke(); break; } } ```
The Sharp Ninja