Reputation: 2070
I have a derived class which is derived from base class,
public class DerivedClass : BaseClass
{
public DerivedClass () {}
public DerivedClass ( BaseClass bc )
{
// The following line is invalid, but I want to achieve something like this
this = bc;
// Error: (this) Cannot assign <This> because this is read only
// Error2: (bc) Cannot implicitly convert Type `BaseClass` to `DerivedClass`
}
}
public class BaseClass
{
public string TestName { get; set; }
public uint TestNumber { get; set; }
public BaseClass () { }
}
then from the Main
method,
static void Main ( string[] args )
{
BaseClass bc = new BaseClass ();
bc.TestName = "dummy test";
bc.TestNumber = 007;
DerivedClass dc = new DerivedClass ( bc );
}
Now my questions are,
this = bc;
)? Thanks!
Upvotes: 0
Views: 3090
Reputation: 7681
It's a bad practice.
That would mean your base class already represents whatever the derived class would be.
I'd recommend composition:
public class TestData
{
public string TestName { get; set; }
public uint TestNumber { get; set; }
}
public class BaseClass
{
protected TestData data;
public BaseClass(TestData data)
{
this.data = data;
}
}
public class DerivedClass : BaseClass
{
public DerivedClass(TestData data)
: base(data)
{
}
}
Upvotes: 1
Reputation: 460370
You cannot do that, you can't use this
in the constructor which refers to the current instance because you're going to construct the object just now. I'd provide appropriate constructors:
public class DerivedClass : BaseClass
{
public DerivedClass() { }
public DerivedClass(string TestName, uint TestNumber)
{
base.TestName = TestName;
base.TestNumber = TestNumber;
}
public DerivedClass(BaseClass bc) : this(bc.TestName, bc.TestNumber) { }
}
So if you're not using the BaseClass
variable in your example at all you don't need it. It's pointless to create a base object just to initialize a child class object.
Upvotes: 1
Reputation: 211
this
is read-only alias - remember to future
you can do like this
public class DerivedClass : BaseClass
{
public DerivedClass () {}
public DerivedClass ( BaseClass bc )
{
TestName=bc.TestName;
TestNumber=bc.TestNumber;
}
}
Is it a right coding practice, if not why? Depends in what you try achieve
Upvotes: 1