I have an enum like this:
public enum Global
{
txt_test = 123
}
Now I want to use a call like this:
var text = lib.Get(Global.txt_test);
Method:
public TextString Get(Enum enumeration)
{
string name = enumeration.ToString();
int index = ?; // (int)enumeration not working
...
}
How to get the index of an enum in this case?
Or am I doing it wrong at all?
Thank you.
Solution:
public TextString Get(Enum enumeration)
{
string name = enumeration.ToString();
int index = Convert.ToInt32(enumeration);
...
}
Enum are convertible to int for retrieving their values:
public TextString Get(Enum enumeration)
{
string name = enumeration.ToString();
int index = Convert.ToInt32(enumeration);
// ...
return null;
}
Note that this will work because your enumeration is type of int by default. Enums can still be other value type like long :
enum Range : long { Max = 2147483648L, Min = 255L };
In this case, the conversion will lost precision.
If you only need the enum value (what you are calling "index") as a string, the best way is to use custom format strings as documented here: http://msdn.microsoft.com/en-us/library/c3s1ez6e%28v=vs.110%29.aspx
For example:
public TextString Get(Enum enumeration)
{
string index = enumeration.ToString("D");
// ...
return null;
}
Related
I have an enum like this:
enum myEnum
{
a = 0101,
b = 2002,
c = 0303
}
I try to get enum value with casting but the 0 at the begin of my enums was removed.
For example I tried this:
var val = (int)myEnum.a;
How can get enum value as string when we have 0 at the beginning of it?
You should rethink your design, but if you want to check your enum integers to a given string, you can use .ToString("0000") to get the string "0101" out of the integer 101.
First, enums are integers, since as their name says, they are enumerations and an enumeration, they are numbers, so enum is integer.
Secondly, you must bear in mind that zero is a null value, since the system is a 01 or 001 like 1, since (basic mathematics) a zero to the left is worthless, so this code is incorrect.
enum myEnum
{
a=0101,
b=2002,
c=0303,
}
The correct way is
enum myEnum
{
a = 0,
b = 1,
c = 2
}
Where the zero is alone, so the system sees it as an index
Now with this, you should only use one of the conversion processes of C#
string strOne = ((myEnum)0).ToString();
string strTwo = ((myEnum)1).ToString();
string strThree = ((myEnum)2).ToString();
Read the MSDN reference https://msdn.microsoft.com/en-us/library/16c1xs4z(v=vs.110).aspx
Enumeration values are always integers. If you need to associate a string with an enumeration value, you can use a dictionary:
enum myEnum { a, b, c }
Dictionary<myEnum, string> lookup = new Dictionary
{
{ a, "0101" },
{ b, "2002" },
{ c, "0303" }
};
To get the string associated with a particular value just use this:
var s = lookup[myEnum.a]; // s = 0101
Another common way to handle this sort of problem is simply to use constants.
class MyConstants
{
public const string a = "0101";
public const string b = "2002";
public const string c = "0303";
}
var s = MyConstants.a; // s = 0101
Try using formatting: you want 4 digits and that's why you can put d4 format string. In order to hide all these implmentation details (cast and formatting) let's write an extension method:
enum myEnum {
a = 0101,
b = 2002,
c = 0303
}
static class myEnumExtensions {
public static string ToReport(this myEnum value) {
return ((int)value).ToString("d4"); // 4 digits, i.e. "101" -> "0101"
}
}
...
myEnum test = myEnum.a;
Console.Write(test.ToReport());
If you always need a specific number of digits you could use string format to get the leading zeros:
var str = String.Format("{0:0000}", (int)myEnum.a);
Or, shorter:
var str = $"{(int) myEnum.a:D4}";
Alternative:
Use an attribute to add extra information to an enum
Attribute:
public class DescriptionAttribute : Attribute
{
public string Name { get; }
public DescriptionAttribute(string name)
{
Name = name;
}
}
Enum:
enum myEnum
{
[Description("0101")]
a = 101,
[Description("2002")]
b = 2002,
[Description("303")]
c = 303
}
Extension Method:
public static string GetDescription(this myEnum e)
{
var fieldInfo = e.GetType().GetField(e.ToString());
var attribute = fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false).FirstOrDefault() as DescriptionAttribute;
return attribute.Name;
}
Usage:
var name = myEnum.a.GetDescription() //will return '0101'
Assuming that the numbers in your enum always have a length of 4
you can use the following
var val = (int)myEnum.a).ToString().PadLeft(4, '0')
Not a duplicate of this.
I want to make a string have a max length. It should never pass this length. Lets say a 20 char length. If the provided string is > 20, take the first 20 string and discard the rest.
The answers on that question shows how to cap a string with a function but I want to do it directly without a function. I want the string length check to happen each time the string is written to.
Below is what I don't want to do:
string myString = "my long string";
myString = capString(myString, 20); //<-- Don't want to call a function each time
string capString(string strToCap, int strLen)
{
...
}
I was able to accomplish this with a property:
const int Max_Length = 20;
private string _userName;
public string userName
{
get { return _userName; }
set
{
_userName = string.IsNullOrEmpty(value) ? "" : value.Substring(0, Max_Length);
}
}
Then I can easily use it whout calling a function to cap it:
userName = "Programmer";
The problem with this is that every string I want to cap must have multiple variables defined for them. In this case, the _userName and the userName (property) variables.
Any clever way of doing this without creating multiple variables for each string and at the-same time, not having to call a function each time I want to modify the string?
Interesting situation - I would suggest creating a struct and then defining an implicit conversion operator for it, similar to what was done in this Stack Overflow question.
public struct CappedString
{
int Max_Length;
string val;
public CappedString(string str, int maxLength = 20)
{
Max_Length = maxLength;
val = (string.IsNullOrEmpty(str)) ? "" :
(str.Length <= Max_Length) ? str : str.Substring(0, Max_Length);
}
// From string to CappedString
public static implicit operator CappedString(string str)
{
return new CappedString(str);
}
// From CappedString to string
public static implicit operator string(CappedString str)
{
return str.val;
}
// To making using Debug.Log() more convenient
public override string ToString()
{
return val;
}
// Then overload the rest of your operators for other common string operations
}
Later you can use it like so:
// Implicitly convert string to CappedString
CappedString cappedString = "newString";
// Implicitly convert CappedString to string
string normalString = cappedString;
// Initialize with non-default max length
CappedString cappedString30 = new CappedString("newString", 30);
Note: This isn't perfect solution, unfortunately - because the implicit conversion doesn't give a way to transfer existing values to the new instance, any CappedString initialized with a non-default length value will need to be assigned to using the constructor, or its length limit will revert back to its default.
Create a class with a string property, and put all of that code there. Then, you can use s.Value anywhere as a string with the needed characteristic.
Something like:
class Superstring
{
int max_Length = 20;
string theString;
public Superstring() { }
public Superstring(int maxLength) { max_Length = maxLength; }
public Superstring(string initialValue) { Value = initialValue; }
public Superstring(int maxLength, string initialValue) { max_Length = maxLength; Value = initialValue; }
public string Value { get { return theString; } set { theString = string.IsNullOrEmpty(value) ? value : value.Substring(0, Math.Min(max_Length, value.Length)); } }
}
and use:
Superstring s = new Superstring("z");
s.Value = "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz";
string s2 = s.Value;
I have the following code
public const string boy = "B";
public const string girl = "G";
private gender(string description, string value)
{
Description = description;
Value = value;
}
public static IEnumerable<gender> GetAll()
{
yield return new gender("Boy", boy);
yield return new gender("Girl", girl);
}
I want to find a way to give my program the string "Boy" and get as a result the string "B" as it should. How is this possible?
var param = "Boy";
var someBoy = GetAll().Where(g => g.Description == param).Select(g => g.Value).Single();
Almost the same as in prevois answer but with check for wrong value received :)
var rez = GetAll().FirstOrDefault(g=>g.Description==string_received);
if(rez==null) throw new ArgumentException();
return rez.Value;
Why do you even want to use an IEnumerable method and a Gender class? You should use an Enum in this situation. Define your Enum like this:
public Enum Gender { Boy, Girl };
Then, you can do this:
Gender gender = Gender.Boy;
string description = gender.ToString();
// If you want to use 'B' as value...
string value = description[0];
Read more about enums here: http://www.dotnetperls.com/enum
I have implemented the enum below:
public enum CaseOriginCode
{
Web = 0,
Email = 1,
Telefoon = 2
}
I would like to get the enum int value by a string. Something like this:
public void setCaseOriginCode(string caseOriginCodeParam)
{
int caseOriginCode = CaseOriginCode.GetEnumByString(caseOriginCodeParam);
// do something with this integer
}
So my input is a string and my output needs to be an int.
Or is it better to implement an dictionary with an key value. The key will be the string and the will be an int.
Please try with the below code snippet.
public void setCaseOriginCode(string CaseOriginCode)
{
int caseOriginCode = (int)(CaseOriginCode)Enum.Parse(typeof(CaseOriginCode), CaseOriginCode);
}
Let me know if any concern.
One thing to note, if after casting you are getting a result of 0, then it is likely because you did not specify a value for your enum.
For example, change this:
public enum AcquisitionChannel
{
Referal,
SearchEngines,
SocialMedia
}
to
public enum AcquisitionChannel
{
Referral = 1,
SearchEngines = 2,
SocialMedia = 3
}
If I understand this question correctly why not just use a switch case?
public CaseOriginCode setCaseOriginCode(string caseOriginCodeParam)
{
switch(caseOriginCodeParam)
{
case "Web":
return CaseOriginCode.Web;
case "Email":
return CaseOriginCode.Email;
case "Telefoon":
return CaseOriginCode.Telefoon;
default:
return default(CaseOriginCode);
}
}
So in practice it would be something like this...
int x = (int)setCaseOriginCode("Web"); // output would be 0
CaseOriginCode y = setCaseOriginCode("Email"); // output would be CaseOriginCode.Email
I cannot create object that contains arrays of property inside object
After I fixed the last problem from the link above, I am faced with a new one, and I tried search one posted but I still struck with it.
In the last line I want to use Result(object) to view and I don't know how to pass it.
The problem is in the last line (return), it said
Cannot implicitly convert type 'decimal'
thank you all :)
namespace finance3.Models
{
public class Expected_and_Risk
{
public void Initialize(int size)
{
Prop = new decimal[size];
AxB = new decimal[size];
Forecast = new decimal[size];
PowAxB = new decimal[size];
Name = new string[size];
}
public decimal[] Prop { get; set; }
public decimal[] Forecast { get; set; }
public string[] Name { get; set; }
public decimal[] AxB { get; set; }
public decimal[] PowAxB { get; set; }
public decimal ExpectValue(Expected_and_Risk abc)
{
int count = abc.Forecast.Count();
Expected_and_Risk Result = new Expected_and_Risk();
Result.Initialize(count);
for (int i = 0 ; i < count ; i++)
{
Result.Name[i] = abc.Name[i];
Result.Prop[i] = abc.Prop[i];
Result.Forecast[i] = abc.Forecast[i];
Result.AxB[i] = abc.Prop[i] * abc.Forecast[i];
decimal a = Result.AxB[i];
decimal sumAxB =+ a;
double temp = (double)(a * a) ;
Result.PowAxB[i] = (decimal)(temp);
}
// here is the problem
return (Result);
}
}
}
You're trying to return your custom object, rather than a decimal.
Change:
public decimal ExpectValue(Expected_and_Risk abc)
to this:
public Expected_and_Risk ExpectValue(Expected_and_Risk abc)
You could fix your compilation error by changing the method's signature:
public Expected_and_Risk ExpectValue(Expected_and_Risk abc) { //...
I have no idea if that makes any sense for your logic, however.
Alternatively if there's a way to convert an Expected_and_Risk object to a single numeric value, you could declare a conversion operator or an instance method to calculate that value, and return it instead:
return (decimal)Result;
or
return Result.DistillToDecimalValue();
Before you even read the rest of this answer, consider the following: Its improbable to return a class constructor as a another form without proper conversion. (Such as a ToDecimal() method, that you might want to create), so change:
public decimal ExpectValue(Expected_and_Risk abc)
to:
public Expected_and_Risk ExpectValue(Expected_and_Risk abc)
Here is my take on this problem:
when you place statement "return (Result);", i believe there are two possible problems.
1) You should have formatted the return statement like so:
return (decimal)Result;
2) You should have converted the object to a decimal, while checking that the result is a valid decimal (You must create a conversion method "ToString()"):
decimal retVal = 0;
if (!decimal.TryParse(Result.ToString(), out retVal)) throw new ArgumentException("Invalid Result"); //put whatever you want inplace of the argumentexception
return retVal;
Although i'm sure the solution at the top will work, if it doesnt just try the other two above.
As dbaseman explained a bit, you are returning a Expected_and_Rick class object, while your method return type is decimal.
And about the loop, you will always return only one Expected_and_Rick object, since you override it in a for loop. I would suggest you to create a List, where T will be Expected_and_Rick class.
public List<Expected_and_Risk> ExpectValue(Expected_and_Risk abc)
{
int count = abc.Forecast.Count();
List<Expected_and_Risk> list = new List<Expected_and_Risk>();
Result.Initialize(count);
for (int i = 0 ; i < count ; i++)
{
Expected_and_Risk Result = new Expected_and_Risk();
Result.Name[i] = abc.Name[i];
Result.Prop[i] = abc.Prop[i];
Result.Forecast[i] = abc.Forecast[i];
Result.AxB[i] = abc.Prop[i] * abc.Forecast[i];
decimal a = Result.AxB[i];
decimal sumAxB =+ a;
double temp = (double)(a * a) ;
Result.PowAxB[i] = (decimal)(temp);
list.Add(Result);
}
return list;
}
And on the other side you can have like:
Expected_and_Risk data = ....
List<Expected_and_Risk> list = ExpectValue(data);