How can I convert from an ASP.NET Unit structure to int in c#? Or reverse?
The Unit type has a Value property. This is a double, but you can cast it to an int if you want. The casting may cause a loss of precision, but you are probably aware of that.
To create a Unit just use the constructor that takes an int.
If you mean the Unit class:
The Unit class can represent values
only between -32768 and 32767.
But it depends if you want the Pixel or Percentage value.
myUnit.Value will get the value as pointed out.
Use the constructor public Unit(int value) to convert back.
If you mean a uint: there's 2 possible obvious ways:
int n = Convert.ToInt32(myUint);
int n = (int)myUint;
For ASP.NET Unit:
unit.IsEmpty ? 0 : Convert.ToInt32(unit.Value);
Use Unit.Value property. It will return double and you can cast it to int
Something like (int)xyz.Value
WEhere xyz is the unit variable
To convert int to unit use new Unit(value)
Probably he need this:
int myInt = 1;
uint myUint = (uint)myInt;
uint myUint = 1;
int myInt = (int)myUint;
The Value property returns a dobule, that you can convert to an integer:
int h = (int)someControl.Height.Value;
However, the conversion might not make sense for some unit types. If you don't know for certain that the unit is of a specific type, you would want to check the Type property first.
Convert.Toint32( UInt );
I guess u meant UInt not Unit
EDIT : Ok thought you meant uint sorry
Related
I receive a string from an external interface which holds an INT32 value. This value represents "-100" - a signed int - and thus, looking like this string "4294967196".
If it would look like "-100" I could use Int32.TryParse() to cast it to a signed value.
But in my case it interprets the values as is and tells me that the value is too big (>2.147.483.647).
Any workaround to get this working? How to tell the parser that the leading 1 is not a number?
Edit: Sorry for being inaccurate. The value I receive is a string that looks like this "4294967196". It represents an Uint32 with the value -100. If the interface would return a string holding "-100" it would be possible to just use Int32.TryParse(). That's what I was trying to express.
Use uint.TryParse() and cast the result to int.
string s = "4294967196";
uint ux;
int x = 0;
if (uint.TryParse(s, out ux))
{
x = (int)ux;
}
// x = -100
I need to convert a string to an integer in windows Phone 7. I tried following code but my app crashed:
int val1 = Convert.ToInt16(str);
Is there another way to do this?
Why does it crash? Do you get an errormessage? What is the actual value of 'str'? Maybe the problem lies there. Also I would opt for ToInt32() as this returns an int, while ToInt16() returns a short. This will not give a problem but it looks more logic. And last, these methods will do the job:
int val1 = Convert.ToInt32("123");
int val2 = int.Parse("123");
int val3 = 0;
int.TryParse("123", out val3);
To convert string to integer, use
string text = "500";
int num = int.Parse(text);
Have you tried
string str = "155";
int retVal;
if(int.TryParse(str, out retVal))
{
// You can now code with it
}
try Convert.ToInt32(str)
Think this will help :)
I think int.TryParse is the way to go. This way you will get to know if the parsing was successful or not by checking the return value. The advantage is since it does not throw any exception you don't have to write any error handling code which makes it simpler and less error prone. I do not personally like code that throws a lot of exceptions as one might easily goof up whilst handling them.
If you are sure to use this on a 32 bit platform, you can try Int32.TryParse() , or if 64- bit platform you may use Int64.TryParse()
I am trying to port a rather large source from VB6 to C#. This is no easy task - especially for me being fairly new to C#.net. This source uses numerous Windows APIs as well as numerous Types. I know that there is no equivalent to the VB6 Type in C# but I'm sure there is a way to reach the same outcome. I will post some code below to further explain my request.
VB6:
Private Type ICONDIRENTRY
bWidth As Byte
bHeight As Byte
bColorCount As Byte
bReserved As Byte
wPlanes As Integer
wBitCount As Integer
dwBytesInRes As Long
dwImageOffset As Long
End Type
Dim tICONDIRENTRY() As ICONDIRENTRY
ReDim tICONDIRENTRY(tICONDIR.idCount - 1)
For i = 0 To tICONDIR.idCount - 1
Call ReadFile(lFile, tICONDIRENTRY(i), Len(tICONDIRENTRY(i)), lRet, ByVal 0&)
Next i
I have tried using structs and classes - but no luck so far.
I would like to see a conversion of this Type structure, but if someone had any clue as to how to convert the entire thing it would be unbelievably helpful. I have spent countless hours on this small project already.
If it makes any difference, this is strictly for educational purposes only.
Thank you for any help in advance,
Evan
struct is the equivalent. You'd express it like this:
struct IconDirEntry {
public byte Width;
public byte Height;
public byte ColorCount;
public byte Reserved;
public int Planes;
public int BitCount;
public long BytesInRes;
public long ImageOffset;
}
You declare a variable like this:
IconDirEntry entry;
Generally, in C#, type prefixes are not used, nor are all caps, except possibly for constants. structs are value types in C#, so that means that they are always passed by value. It looks like you're passing them in to a method that's populating them. If you want that usage, you'll have to use classes.
I'm not exactly sure what your issue is but this is a small ex of how to use a struct.
struct aStrt
{
public int A;
public int B;
}
static void Main(string[] args)
{
aStrt saStrt;
saStrt.A = 5;
}
Your question is not clear ..
What issues are you facing when you are using either struct or class and define those field members? Are you not able to access those members using an instance created for that class ??
Else, declare the class as static and make all the members inside the class also as static , so that u can access them without any instance being created!!
Maybe you trying to get something like this?
struct IconDirEntry
{
public byte Width;
// etc...
}
IconDirEntry[] tICONDIRENTRY = new IconDireEntry[tICONDIR.idCount - 1];
I have a generic class (C#),
class MyClass<T> where T : struct, IComparable<T>
{
public T filelocation;
}
T can be either UInt32 or UInt64 (nothing else).
I need to convert filelocation to a long to seek in a file...
I have tried the following
long loc = (T)myclass.filelocation;
long loc = (T)(object)myclass.filelocation;
But nothing seems to work...
Any ideas?
Call Convert.ToInt64.
Writing (object)fileLocation creates a boxed UInt32.
Boxed value types can only be unboxed to their original value types, so you cannot cast it in one step to long.
You could write (long)(ulong)fileLocation, but that will fail for a uint for the same reason.
Try Convert.ToInt64.
long loc = Convert.ToInt64(myclass.filelocation);
You may use TryParse:
long lng;
int testNum = 55;
long.TryParse(testNum.ToString(),out lng);
with your class definition if i write something like
public MyClass<long> myclass = new MyClass<long>();
public long returnLong()
{
return myclass.filelocation;
}
myclass.fileLocation return long by defult
say I have the following declarations:
public enum Complexity { Low = 0, Normal = 1, Medium = 2, High = 3 }
public enum Priority { Normal = 1, Medium = 2, High = 3, Urgent = 4 }
and I want to code it so that I could get the enum value (not the index, like I earlier mentioned):
//should store the value of the Complexity enum member Normal, which is 1
int complexityValueToStore = EnumHelper.GetEnumMemberValue(Complexity.Normal);
//should store the value 4
int priorityValueToStore = EnumHelper.GetEnumMemberValue(Priority.Urgent);
How should this reusable function look like?
tia!
-ren
Revised answer (after question clarification)
No, there's nothing cleaner than a cast. It's more informative than a method call, cheaper, shorter etc. It's about as low impact as you could possibly hope for.
Note that if you wanted to write a generic method to do the conversion, you'd have to specify what to convert it to as well: the enum could be based on byte or long for example. By putting in the cast, you explicitly say what you want to convert it to, and it just does it.
Original answer
What do you mean by "index" exactly? Do you mean the numeric value? Just cast to int. If you mean "position within enum" you'd have to make sure the values are in numeric order (as that's what Enum.GetValues gives - not the declaration order), and then do:
public static int GetEnumMemberIndex<T>(T element)
where T : struct
{
T[] values = (T[]) Enum.GetValues(typeof(T));
return Array.IndexOf(values, element);
}
You can find the integer value of an enum by casting:
int complexityValueToStore = (int)Complexity.Normal;
The most generic way I know of is to read the value__ field using reflection.
This approach makes no assumptions about the enum's underlying type so it will work on enums that aren't based on Int32.
public static object GetValue(Enum e)
{
return e.GetType().GetField("value__").GetValue(e);
}
Debug.Assert(Equals(GetValue(DayOfWeek.Wednesday), 3)); //Int32
Debug.Assert(Equals(GetValue(AceFlags.InheritOnly), (byte) 8)); //Byte
Debug.Assert(Equals(GetValue(IOControlCode.ReceiveAll), 2550136833L)); //Int64
Note: I have only tested this with the Microsoft C# compiler. It's a shame there doesn't appear to be a built in way of doing this.
I realize this isn't what you asked, but it's something you might appreciate.
I discovered that you can find the integer value of an enum without a cast, if you know what the enum's minimum value is:
public enum Complexity { Low = 0, Normal = 1, Medium = 2, High = 3 }
int valueOfHigh = Complexity.High - Complexity.Low;
This wouldn't work with Priority, unless you added some minimal value of 0, or added 1 back:
public enum Priority { Normal = 1, Medium = 2, High = 3, Urgent = 4 }
int valueOfUrgent = Priority.Urgent - Priority.Normal + 1;
I find this technique much more aesthetically appealing than casting to int.
I'm not sure off the top of my head what happens if you have an enum based on byte or long -- I suspect that you'd get byte or long difference values.
If you want the value, you can just cast the enum to int. That would set complexityValueToStore == 1 and priorityValueToStore == 4.
If you want to get the index (ie: Priority.Urgent == 3), you could use Enum.GetValues, then just find the index of your current enum in that list. However, the ordering of the enum in the list returned may not be the same as in your code.
However, the second option kind of defeats the purpose of Enum in the first place - you're trying to have discrete values instead of lists and indices. I'd rethink your needs if that is what you want.
This is the most simple way to solve your problem:
public static void GetEnumMemberValue<T>(T enumItem) where T : struct
{
return (int) Enum.Parse(typeof(T), enumItem.ToString());
}
It works for me.