Austin Salonen
Austin Salonen

Reputation: 50215

C#: Specifying behavior for the "default" keyword when using generics

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?

Upvotes: 0

Views: 758

Answers (3)

harpo
harpo

Reputation: 43158

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"

Upvotes: 2

recursive
recursive

Reputation: 86064

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.

Upvotes: 4

Smart Alec
Smart Alec

Reputation:

No you cant. Sorry.

Upvotes: 2

Related Questions