Morten
Morten

Reputation: 95

Member initialisation in c#

I have two classes, class A and class B.

public class A
{ 
    public int someNumber;

    public A(int a)
    {
        someNumber = a; 
    }
}

Now class B has a field that is an object of class A. In C++ it is possible to do this:

public class B
{
    public A foo;

    public B(int a) : foo(a) { }
}

But this doesnt work in C#. So how can one solve this problem in C# without using a default constructor in class A. To be more precise, how is it possible to write a constructor for class B that takes as parameter the someNumber value of foo?

Upvotes: 0

Views: 59

Answers (1)

Christos
Christos

Reputation: 53958

You could try something like this:

public class B 
{

    public A thing;

    public B(int a)
    {
        thing = new A(a);
    }
}

Upvotes: 5

Related Questions