简体   繁体   中英

conditional initialization of class member using c# object initialization

I am having a simple class with 3 not null integer members

public class Test
{
    public int Test1 { get; set; }
    public int Test2 { get; set; }
    public int Test3 { get; set; }
}

Now I want to use something like this

        int? var1 = null;
        int var2 = 2;
        int var3 =5;
       var t =  new Test
        {
            Test1 = var1, // (error) Initialize Test1 only when var1 is not null
            Test2 = var2,
            Test3 = var3
        };

ie I just want to initialize member Test1 only if var1 is not null, so somehow I need to put a check while initialization. I know its a simple question and can be done in diifferent ways but as I am refactoring the existing code and generalizing it, I need solution through Object Initialization only. Looking simple to me but somehow could not able to find solution by myself

Not much experienced programmer, so really appreciate any help

That wouldn't compile anyway, I don't think. But either way the value will get the default value of an int if you don't initialize it. An equivalent would be:

    int? var1 = null;
    int var2 = 2;
    int var3 =5;
    var t =  new Test
    {
        Test1 = var1.GetValueOrDefault(),
        Test2 = var2,
        Test3 = var3
    };

The default value of Test1 is zero so you could use the null-coallescing operator:

var t =  new Test {
    Test1 = var1 ?? 0,
    Test2 = var2,
    Test3 = var3
};

If the class might specify a default besides the default int, or for another reason you need to not call the property setter at all when var1 is null , then you can't use the object initialization syntax for Test1 . (I'm aware that the question says to use object initialization, but just in case that can't work...) Eg

public class Test
{
    public int Test1 { get; set; }
    public int Test2 { get; set; }
    public int Test3 { get; set; }

    public Test()
    {
        Test1 = -1;
    }
}

var t =  new Test
    {
        Test2 = var2,
        Test3 = var3
    };
if (var1 != null) // or (var1.HasValue)
    t.Test1 = var1.Value;

If this isn't the case, you might go with this or any other answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM