C #: specifying behavior for "default" keyword when using generics

Can I specify my own default object instead? I would like to define my own default properties for certain objects.

For example, if I have a foo object with bar and baz properties, instead of keeping null by default, I would like it to be an instance of foo with bar set to "abc" and baz set to "def" - - is it possible?

0


source to share


3 answers


You must use the constructor to get this functionality. Thus, you cannot use the default settings.

But if your goal is to provide a certain passed type state in a generic class, there might still be hope. If you want the passed type to be workable, use a general constraint. The new () constraint. This ensures that there is a public parameterless 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 cannot use this to get parameterized constructors, only parameterless constructors.

+5


source


No, you cannot. Unfortunately.



+2


source


You cannot use the "default", but it may not be the right tool.

To clarify, "default" will initialize all reference types to zero.

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 achieve what you want if you want type T to have 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"

      

+2


source







All Articles