biox
biox

Reputation: 1566

Make class invisible outside of assembly

Lets say I have class Dog:

public class Dog {
    public String Breed { get; set; }
    public String Color { get; set; }
    ...
}

And a class Animal:

public class Animals {
    public Dog[] Dogs { get; set; }

    public Dog[] GetDogs() {
        ...
        return Dogs;
    }
    ...
}

The above to classes are in my class library and I added it as reference to my project.. Everything works fine but what I want is whoever uses this library should not be able to use class Dog, I mean he should not be able to do something like Dog dog = new Dog();. I tried to make it internal, but then, I must also write internal in Animals class and if I do this I can't use the GetDogs() method.

Any suggestions?

Upvotes: 3

Views: 2694

Answers (5)

S2S2
S2S2

Reputation: 8502

You can make the Dog class as public but its default constructor as internal:

public class Dog
{
    internal Dog() {}
}

Using internal on the default contstructor will restrict initializing it from the code outside the assembly.

Upvotes: 1

Shane Haw
Shane Haw

Reputation: 723

if animals is the only class that uses dog then you could make dog a nested private class in animals and therefore only accessible in animals. But why do you want to do this?

Upvotes: 1

Adriaan Stander
Adriaan Stander

Reputation: 166356

Change Dog to

public class Dog
{
    internal Dog()
    {

    }
    public String Breed { get; set; }
    public String Color { get; set; }
}

then

Dog d = new Dog();

will produce

The type 'Dog' has no constructors defined. Cannot access internal constructor 'Dog' here.

Upvotes: 3

nikodz
nikodz

Reputation: 727

Make internal constructor for Dog class. internal Dog(){}. Then only that assembly can create new Dog(), but everyone can use Dog class.

Upvotes: 5

Vadim
Vadim

Reputation: 2865

If you wish to return Dogs you'll have to keep it public. If you wish to prevent creating Dogs outside of an assembly - make his constructor internal.

Another option is to use interfaces.

Upvotes: 1

Related Questions