Numeric Wrapper Objects in C#

D

Dylan Phillips

I've often used Java's Numeric Wrapper Objects when numeric properties can have a null state. This is very useful with optional properties for which 0 has meaning. For example:

//Java Code
class SomeObject
{
protected Double _optionalAttribute;

public Double getOptionalAttribute
{return _optionalAttribute;}
public Double setOptionalAttribute (double someValue)
{_optionalAttribute = new Double(someValue);}
}

class SomeCode
{
public static void main(string[] args)
{
SomeObject object = new SomeObject();
if (object.getOptionalAttribute == null) {System.out.println("Attribute is not set");}
else
{
if (object.getOptionAttribute.doubleValue() == 0) {System.out.println("Attribute is set to zero");}
else {System.out.println("Attribute is set to" + object.getOptionalAttribute.toString());}
}
}
}

In C#, I cannot test a System.Double for null. Any ideas on how others have solved this? I've been avoiding it for about 3 weeks now, and my code is getting sloppy.

Thanks,
Dylan
 
Z

Zhanyong Wan [MSFT]

The Nan trick is cute, but doesn't work for integer types. If you need to
wrap an integer, you need something else.

Do you know that you can cast any value type into an object and back? This
is called boxing and unboxing. e.g.

double x = 2.5;
object xObj = x; // boxing is done automatically.
...
if ( xObj == null ) ...
x = (double) xObj; // you have to explicity unbox a boxed value.

If you don't like the fact that all value types are boxed as object (and
therefore cannot be told apart statically), you can define your own
Java-style wrapper classes:

public class DoubleObject
{
private double value;
public DoubleObject( double x ) { this.value = x; }
public double GetValue() { return this.value; }
}

- Zhanyong Wan

Visual Studio and .NET Setup

This posting is provided "AS IS" with no warranties, and confers no rights.
Use of included samples (if any) is subject to the terms specified at
http://www.microsoft.com/info/cpyright.htm
--------------------
| From: "Dylan Phillips" <[email protected]>
| References: <[email protected]>
<#[email protected]>
| Subject: Re: Numeric Wrapper Objects in C#
| Date: Sat, 30 Aug 2003 12:25:40 -0400
|
| Wonderful! It's so simple it did not even occur to me! Sir, I owe you a
| beer.
|
| Thanks,
| Dylan
| | > In article <[email protected]>, (e-mail address removed)
| > (Dylan Phillips) writes:
| >
| > > In C#, I cannot test a System.Double for null. Any ideas on how
others
| > > have solved this?
| >
| > Could you use the constant Double.Nan ? ("NaN" = "not a number".)
| >
| > You'd still lose the distinction between null and NaN, though,
| > but perhaps that doesn't matter?
| >
| > /Gomaw
| >
|
|
|
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top