views:

58

answers:

2

How come setting OrganizationName = null does not work? I am doing a union and would like to set the value to null.

from a in Activities
select new 
{
    a.ActivityID,
    a.ActivityName,
    a.OrganizationID,
    OrganizationName = null
}
A: 

You need to set the OrganizationName to null assuming that it a property of a like so. a.OrganizationName = null

msarchet
Thanks, that worked.
scottrakes
+2  A: 

You can't actually do this:

It is a compile-time error for an expression in an anonymous object initializer to be of the null type.

However, you can do this:

from a in Activities 
select new  
 { 
  a.ActivityID, 
  a.ActivityName, 
  a.OrganizationID, 
  OrganizationName = (object)null 
 } 

This is because in an anonymous object it needs to be able to determine the type of that variable, and it doesn't want to assume it is just object. In fact for your example you may not even want that (you might want a string or a complex type e.g. Organisation). This is the same problem as going:

var a = null; /* What am I oh cruel world */

Having said that I can't see the utility of what you're trying to do here so perhaps if you elaborate on your use-case a more useful answer may be found.

References:

Graphain
FYI: the reason is because the compiler has no way to know what type you want `OrganizationName` to be. Casting it to `(object)` you tell the compiler you want `OrganizationName` to be of type `object`, but you can cast it to any type you like (by the name of the property, I assume you want `string`)
Dean Harding
You can also use default(string) which I've always found to be more intuitive than casting a null.
Josh Einstein
@Josh Yeah, although a novice might read `default(string)` as `String.Empty`.
Graphain
OrganizationName = (string)null works. Thanks.
scottrakes