0

I'm new of the Object Oriented Programming methods:

I have a class MyClass1 as follow:

public class MyClass1
{
    public int id { get; set; }
    public string name { get; set; }
}

There is also a class MyClass2 defined as:

public class Myclass2
{
    public int id { get; set; }
    public string name { get; set; }

    public Myclass2(MyClass1 m) { }

}

MyClass2 exists only if exists MyClass1, because in MyClass2 I need some properties of the MyClass1.

The best for me will be some like this:

MyClass1.MyClass2 = new MyClass2();

Ofcourse the constructor of MyClass2 should take MyClass1.

What is the best method to achieve this using C# Object Oriented Programming ?

4
  • 1
    public class Myclass2 : MyClass1 {.... Commented Jul 20, 2012 at 14:10
  • Look at using inheritance in c# msdn.microsoft.com/en-us/library/ms173149(v=vs.80).aspx Commented Jul 20, 2012 at 14:10
  • I think this wants the homework tag, and some clarification, before we see a flood of upvotes. Commented Jul 20, 2012 at 14:12
  • based on your example its best to delete MyClass2, it adds nothing. How would MyClass2 be different? Commented Jul 20, 2012 at 14:18

2 Answers 2

4

Inheritance:

public class Myclass2 : Myclass1
{
    public Myclass2() { }
}

You may also want to look at Nested types

public class Myclass2
{
    public class Myclass1
    { 
        Myclass1(){}
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

It looks like MyClass2 should inherit from MyClass1, but you've not really explained what you are trying to accomplish well enough to be sure that's what you want.

1 Comment

agreed: inner class might be a better option for OP depending on usage

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.