ValueType

  • Thread starter Thread starter Shawn B.
  • Start date Start date
S

Shawn B.

Greetings,

Is it possible to create a custom ValueType object in C#? Or must I use
managed C++ for that?



Thanks,
Shawn
 
In the book "Essential Guide to Manged Extensions for C++" page 55 "In MC++,
class that are meant to be created on the stack are called value types. In
this capter you will learn how to create value types, convert them to gc
classes via boxing, and implent interfaces by deriving a value type from
them." On the next page it says "A value type is declared with the keyword
__value followed by class or stuct... for example:

"#using <mscorlib.dll>
__value class Fraction
{
....
}

The value type Fraction can then be created on the stack:

int main()
{
Fraction f(1,2);
}
....

So according to this book (written by people on the MC++ compiler team) it
indicates they can be created in MC++. But I take it not possible in C#
unless I create a struct?

As well, is it a compiler trick that I can say
int i = 10;
int j; j=10;

instead of
int i = new System.Int32();

?


Thanks,
Shawn
 
As well, is it a compiler trick that I can say
int i = 10;
int j; j=10;

instead of
int i = new System.Int32();

?

The native value types have special treatment due (at least) to their own IL
instructions for loading onto the stack. But if it's any consolation you
can do your own "compiler magic" with conversion operators:

using System;
namespace ConvertableValueType
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
MyValueType value = new byte[] {0xD0, 0x0F, 0x49, 0x40, 0x0, 0x0, 0x0, 0x1};
Console.WriteLine(value.MySingle);
Console.WriteLine(value.MyInt32);
}
}
public struct MyValueType
{
public MyValueType(float fValue, int iValue)
{
MySingle=fValue;
MyInt32=iValue;
}
public float MySingle;
public int MyInt32;
public static implicit operator MyValueType(Byte[] buffer)
{
return new MyValueType(BitConverter.ToSingle(buffer, 0),
BitConverter.ToInt32(buffer, 4));
}
}
}
 
Back
Top