tags:

views:

478

answers:

3

Is it possible to specify my own default object instead of it being null? I would like to define my own default properties on certain objects.

For example, if I have an object foo with properties bar and baz, instead of default returing null, I'd like it to be an instance of foo with bar set to "abc" and baz set to "def" -- is this possible?

+2  A: 

No you cant. Sorry.

+4  A: 

You have to use a constructor to get that functionality. So, you can't use default.

But if your goal is to ensure a certain state of the passed type in a generic class, there may still be hope. If you want to ensure the passed type is instanti-able, use a generic constraint. The new() constraint. This ensures that there is a public parameter-less constructor for type T.

public class GenericClass<T> where T : new() {
    //class definition

    private void SomeMethod() {
        T myT = new T();
        //work with myT
    }
}

Unfortunately, you can't use this to get constructors that have parameters, only parameter-less constructors.

recursive
default(T) is still null, however!
Mehrdad Afshari
+1 for reading my mind on what I really wanted to do. You get the checkmark as well. Thanks!
Austin Salonen
Yes. True. The first line of my response says that it's not possible using default, but I guessed what the question was really after, and it's possible to achieve using a different method, not default. Your approach is on the right track, but the key is the new() generic constraint.
recursive
Shucks, I guess recursive can be faster! :)
harpo
note that for structs parameterless constructors are not allowed, so you have to do more coding if you need same behavior for structures.
DK
+2  A: 

You can't with "default", but maybe that's not the right tool.

To elaborate, "default" will initialize all reference types to null.

public class foo
{
    public string bar = "abc";
}

public class Container<T>
{
    T MaybeFoo = default;
}

a = new Container<foo>();

// a.MaybeFoo is null;

In other words, "default" does not create an instance.

However, you can perhaps achieve what you want if you're willing to guarantee that the type T has a public constructor.

public class foo
{
    public string bar = "abc";
}

public class Container<T> where T : new()
{
    T MaybeFoo = new T();
}

a = new Container<foo>();

Console.WriteLine( ((Foo)a.MaybeFoo).bar )  // prints "abc"
harpo