Say, we have two classes:
public class A
{
protected static readonly int DefaultValue = 123;
int value;
public A()
{
value = DefaultValue;
}
public A(int _value)
{
value = _value;
}
}
public class B : A
{
public B(XElement x)
: base(x.Element("int") == null
? A.DefaultValue
: (int)x.Element("int"))
{
}
}
I understand that I could make a parameterless constructor for class B::
public B():base()
{
}
and have smth like this:
B objB = (x.Element("int") == null)?new B():new B((int)x.Element("int"));
but I’d love to have this logic encapsulated in class B.
Also I see I can do some kind of static factory method and have it encapsulated (and even make those class B constructors private if necessary):
public static B GetInstance(XElement x)
{
return (x.Element("int") == null)?new B():new B((int)x.Element("int"));
}
But I’d love to be able to have smth like the following pseudo code:
public class A
{
//don't need this anymore
//protected static readonly int DefaultValue = 123;
int value;
public A()
{
value = 123;
}
public A(int _value)
{
value = _value;
}
}
public class B : A
{
public B(XElement x)
: x.Element("int") == null
? base()
: base((int)x.Element("int"))
{
}
}
Or is there any other approach which could do the same thing as nice and even better?
Have you tried playing around with a null int (int?) in the Class A constructor? With a optional parameter you might be able get away with one constructor.