all groups > dotnet clr > september 2003 >
You're in the

dotnet clr

group:

Casting ValueType variable to primitive type


Casting ValueType variable to primitive type Célio Cidral Junior
9/30/2003 10:02:16 AM
dotnet clr:
Hello.

(I don't know if this is the right newsgroup to post this message, so sorry
if I'm cross-posting).

I am writing a base class which has an abstract property of some type. This
property must be overrided and have different return types at base classes,
as follows:

public abstract class NumericTextBox : TextBox
{
public abstract ValueType Value
{
get;
}
}

public class DecimalTextBox : NumericTextBox
{
public override Decimal Value
{
get
{
return 123;
}
}
}

public class DoubleTextBox : NumericTextBox
{
public override Double Value
{
get
{
return 123;
}
}
}

I know the previous code won't work. Anyway, how can I do that? What's the
right way to do that?

Thank you in advance.

Celio Cidral Junior
WEG Eletric
Brazil

RE: Casting ValueType variable to primitive type jenh NO[at]SPAM online.microsoft.com
10/3/2003 6:26:58 PM
You could box it and return an Object, then unbox it when you need to use
it. C# will implicitly box a value type to a reference type, but you must
explicitly unbox it.

public abstract class NumericTextBox
{
public abstract Object Value
{
get;
}
}

public class DecimalTextBox : NumericTextBox
{
public override Object Value
{
get
{
return (decimal)123;
}
}
}

public class DoubleTextBox : NumericTextBox
{
public override Object Value
{
get
{
return 123.123d;
}
}
}


public class Test
{
public static void Main()
{
NumericTextBox box1 = new DecimalTextBox();
NumericTextBox box2 = new DoubleTextBox();
Object[] values = new Object[2];
values[0] = box1.Value;
values[1] = box2.Value;
for (int i=0; i < values.Length; i++)
{
if (values[i] is System.Decimal)
{
Decimal decimalValue = (decimal)values[i];
Console.WriteLine("Value " + i + " is decimal value " +
decimalValue);
}
else if (values[i] is System.Double)
{
Double doubleValue = (double)values[i];
Console.WriteLine("Value " + i + " is double value " +
doubleValue);
}
else
{
Console.WriteLine("Value " + i + " is unknown type " +
values[i]);
}
}
}
}
AddThis Social Bookmark Button