Search code examples
c#propertiesinstancecurly-bracesgeneric-type-argument

Filling in properties using braces after using Factory Method


Is it possible to create a method that returns a new object, where i can still use:

{ variable 1 = "content1", variable2 = "content2" }

Because for now after getting the object, i have use the following instead:

tempObject.variable1 = "content1";
tempObject.variable2 = "content2";

So for instance:

var tempNewObject = MDBShorterManager.Create<TblUser>() { variable1 = "content1", variable2 = "content2" };

My current methode:

public T Create<T>() where T : MDBShorter
{
    try
    {
        var tempObject = (T)Activator.CreateInstance(typeof(T));

        tempObject.mdbShorterManager = this;

        try
        {
            actionInjectDataToMDBShorter?.Invoke(tempObject);
        }
        catch(Exception ex)
        {
            ErrorLog.cw(ex.Message);
        }

        return tempObject;
    }
    catch (Exception ex)
    {
        ErrorLog.cw(ex.Message);
        return null;
    }
}

Solution

  • No, by the time of creation of the post, there's no such thing in C#. Maybe they will add that kind of syntax sugar in the future, but currently it can only be used with the "new" keyword next to the constructor call.