Click here to Skip to main content
15,920,956 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
public class class1
{
prop1;
prop2;
prop3;
}

public class class2
{
prop4;
prop5;
prop6;
}

now I want class3 have Just these properties:

public class class3
{
prop1;
prop2;
prop6;
}

in inheritance, class3 have other properties implicitly that i don't need them...
to be clear,I have made some tables in sql and for each table, a class in my windows form Program. I want transfer data between DB and my c# program and I select just some fields of each tables in my query. to save data returned by query, I need class3.
I tried inheritance,but I had to Initialized all 6 prop's and I don't want this.
Posted

First of all, your code samples won't compile, but the idea is clear.

You cannot get what you want (and Solution 1 is totally unrelated to that), because this is not how inheritance work. The idea is not to fight against OOP, but to make it work for you. In your simple case, you just need to build class hierarchy suitable to your design. For example:

C#
class MyVeryBase {
   internal int prop1 { get; set; }
   internal int prop2 { get; set; }
}

//to get class3, you will need to add prop6:
class class3 : MyVeryBase {
   internal ulong prop6 { get; set; }
}

//to get class1, you will need to add prop3:
class class3 : MyVeryBase {
   internal string prop3 { get; set; }
}

//and class2 you can, for example, create from scratch:
class MyVeryBase {
   internal System.Text.StringBuilder prop4 { get; set; }
   internal byte prop5 { get; set; }
   internal char prop6 { get; set; }
}


If you really need to combine more that two classes (for example, to get the same prop6), you need something to provide multiple inheritance (read about it). In .NET, you get only so called, weak form of multiple inheritance, which you can get only for interface. Read about them.

—SA
 
Share this answer
 
Along with Sergey's crisp response, I suggest you read this nicely written article about Simulating Multiple Inheritance in C#[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900