23

As I understand default(object) where 'object' is any reference type always returns null, but can I specify what a default is? For instance, I want default(object) == new object();

6
  • 1
    No, it's not possible. Can you tell us the end goal here, i.e. why you would want this feature?
    – Ani
    Nov 1, 2010 at 2:28
  • No. And why would you need to do that? If the object is null, simply assign a new one! Nov 1, 2010 at 2:28
  • 1
    Just to be able to say FirstOrDefault() and never get a null. Guess I'll just write a new extension method then. Nov 1, 2010 at 2:30
  • 1
    In that case, do mySequence.FirstOrDefault(predicate) ?? fallback. Alternatively, you can write / find implementations for FirstOrFallBack, e.g. from Zen LINQ extensions.
    – Ani
    Nov 1, 2010 at 2:31
  • @Ani, sure. Just don't want to do that more than once. My question is more out of curiosity than practicality. Nov 1, 2010 at 2:33

3 Answers 3

34

No. default(type) will always return the same thing - a "zero'ed out" version of that type. For a reference type, this is a handle to an object that is always set with a value of zero - which equates to null. For a value type, this is always the struct with all members set to zero.

There is no way to override this behavior - the language specification is designed this way.


Edit: As to your comment:

Just to be able to say FirstOrDefault() and never get a null.

I would not recommend this in any case. Users expect FirstOrDefault() to return null on failure. It would be better to write your own extension method:

static T FirstOrNewInstance<T>(this IEnumerable<T> sequence) where T : class, new()
{
     return sequence.FirstOrDefault() ?? new T();
} 
8

Sorry, I'm not Jon Skeet...

But anyway, the answer is "no you can't"

4
  • 8
    Normally Jon Skeet explains why (or why not in this case) :)
    – PostMan
    Nov 1, 2010 at 2:38
  • 1
    @PostMan, like I said, I'm not Jon Skeet ;). Anyway, I don't think there's anything to explain here... it's just not possible. Nov 1, 2010 at 2:54
  • 1
    Just make it up, you'll be fine :) But yes, I agree, there is no explanation other than you can't. (other than it's a design decision)
    – PostMan
    Nov 1, 2010 at 3:44
  • 3
    Jon Skeet will give the quick answer first (as in "no, you can't") in order to come with an answer first, and then edit the answer to include the why.
    – awe
    Aug 23, 2012 at 7:50
-1

You can do something like this, it will call parameterless constructor

    public static T NewInstanceByType<T>(Type type) => (T)Activator.CreateInstance(type);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.