C
C#3y ago
Klarth

Nullable approach with property defined in base and initialized in derived classes [Answered]

Is there an approach for the Base.Some property besides changing it to SomeType? or suppressing with = null!;. I want to defer the creation and leave it up to a derived class.
public abstract class Base
{
public SomeType Some { get; set; }
}

public class DerivedA : Base
{
public DerivedA()
{
Some = new SomeType(1, 2, 3);
}
}

public class DerivedB : Base
{
public DerivedB()
{
Some = new SomeType(9, 8, 7);
}
}

public class SomeType
{
public SomeType(int a, int b, int c) { }
}
public abstract class Base
{
public SomeType Some { get; set; }
}

public class DerivedA : Base
{
public DerivedA()
{
Some = new SomeType(1, 2, 3);
}
}

public class DerivedB : Base
{
public DerivedB()
{
Some = new SomeType(9, 8, 7);
}
}

public class SomeType
{
public SomeType(int a, int b, int c) { }
}
16 Replies
WhiteBlackGoose
required I think, did it land yet?
Klarth
KlarthOP3y ago
Does that work in derived instances? 🤔
WhiteBlackGoose
but you can just make a constructor honestly
Klarth
KlarthOP3y ago
I was thinking of just required init;
WhiteBlackGoose
since you set this property anyway
Klarth
KlarthOP3y ago
Constructor isn't good enough for the actual scenario. There's some logic involved.
WhiteBlackGoose
ctor which takes in your SomeType instance which you can generate with any logic
Klarth
KlarthOP3y ago
I can't use logic inside of the type's ctor to create the instance and pass the created instance to the parent ctor...I think.
WhiteBlackGoose
should be able to I think 🤔
MODiX
MODiX3y ago
Oryp4ik#0120
REPL Result: Success
public abstract class Hehehe
{
public Hehehe(int aa) { }
}

public class Gg : Hehehe
{
public Gg(int a, int b) : base(a + b) {}
}
public abstract class Hehehe
{
public Hehehe(int aa) { }
}

public class Gg : Hehehe
{
public Gg(int a, int b) : base(a + b) {}
}
Compile: 479.328ms | Execution: 29.686ms | React with ❌ to remove this embed.
WhiteBlackGoose
builds
Klarth
KlarthOP3y ago
That's a pretty simple expression, but it looks like required does the job.
WhiteBlackGoose
Good to hear. I have no experience with required, so couldn't help
Klarth
KlarthOP3y ago
Need to use [SetsRequiredMembers] on the ctor, too, if you don't want to use an object initializer.
Klarth
KlarthOP3y ago
Accord
Accord3y ago
✅ This post has been marked as answered!

Did you find this page helpful?