MAC
MAC

Reputation: 6577

using class as a property?

how we can use one class, which is inside into another class as property? i want only theoratical explanation and one small example.

Upvotes: 3

Views: 8973

Answers (6)

Daniel Earwicker
Daniel Earwicker

Reputation: 116764

You mention setting up relations between Teachers and Students (hopefully appropriate ones).

This could be one-to-one for private tuition, or it could be one-to-many if the students attend classes with the teachers, or it could be many-to-many if students attend several classes.

By the way, tell your teacher this is a bad example to set, because it's so ambiguous, and because the word "classes" is a nightmare domain term given the existing meaning of the word class in OO.

Upvotes: 0

odiseh
odiseh

Reputation: 26547

Suppose that you have a class (model) that is a way to reach to other classes. So you should have a definition (property) of those classes in the model. I use this theory in my applications. You can imagine the model as father of a big family who can order to others to do specific tasks.

Public Class Father
{
 private Child _Child=null;
 public Child Child
 {
   get{
       if(_Child==null) _Child=new Child();
       return _Child;
      }
 }
}
Public Class Child
{
  Public void StudyLessons()
  {
   .....
  }

}

Upvotes: 0

chikak
chikak

Reputation: 1732

Class B is nested inside Class A and we have a property BProperty in Class A which gives an instance of Class B.

public class A
{
    public class B
    {
        string m_b1;
        public string B1
        {
            get { return m_b1; }
            set { m_b1 = value; }
        }
    }
    B m_b = new B();
    public A()
    {
        m_b.B1 = "Hello World";
    }

    public B BProperty
    {
        get { return m_b; }
        set { m_b = value; }
    }
}

class Program
{
    static void Main(string[] args)
    {
        A a = new A();
        Console.WriteLine(a.BProperty.B1);
    }
}

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1504122

You can use a nested type as a property, but if they're within the same class they can't have the same name:

public class Invalid
{
    public Nested Nested { get { return null; } }        
    public class Nested {}
}

public class Valid
{
    public Nested NestedFoo { get { return null; } }        
    public class Nested {}
}

Upvotes: 2

Paul van Brenk
Paul van Brenk

Reputation: 7559

public class Foo{ 
    public string Name;
}

public class Bar{
    public Foo MyFoo{ get; set; }
}

Upvotes: 3

Mehrdad Afshari
Mehrdad Afshari

Reputation: 422320

You mean a nested class used as a type of a property? As long as the access modifier of the property is at most as restrictive as the type of the property, you can do this.

Simply, you should be able to access the type if you can see the property.

Upvotes: 3

Related Questions