Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How create a class that is abstract, but not internally

Tags:

c#

Is this possible in c# somehow? This is the exact case I need it for: He (the user) must not be able to create instances of this class. However, I want to be able to create instances of this class inside my project. (hence: internally) Other classes should be able to inherit from it. I want to force the user to only use the bigger Sound class. The big "BUT": The user must be able to use instances of this class if I give it to him, that's why I can't just make it internal and be done with it. Neither can I make it abstract, because I want to make copies myself. I thought about giving the user only interfaces like IChannel back, but that doesn't solve my problem that he shouldn't be able to make an instance of Channel. He will still be able to see the class if he looks for it, and if he is adventureous enough even try to create an instance. But as I mentioned before: I can't make it abstract because I need to make copies internally.

Appreciate your help!

like image 801
Blub Avatar asked Jul 01 '10 14:07

Blub


People also ask

Is it possible to have an abstract class without abstract?

And yes, you can declare abstract class without defining an abstract method in it. Once you declare a class abstract it indicates that the class is incomplete and, you cannot instantiate it. Hence, if you want to prevent instantiation of a class directly you can declare it abstract.

Can you instantiate an abstract class and what is an inner class?

Abstract classes cannot be instantiated, but they can be subclassed. When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, then the subclass must also be declared abstract .

Can abstract classes be partially implemented?

An abstract class is a "partially implemented" class which other classes can inherit from, but if they do, they must provide their own implementations for any method in the abstract class that is not already implemented. An abstract class is defined using the abstract keyword.

Can abstract class be internal?

An Abstract class can have access modifiers like private, protected, and internal with class members. But abstract members cannot have a private access modifier. An Abstract class can have instance variables (like constants and fields). An abstract class can have constructors and destructors.


2 Answers

You should be able to declare the constructor as internal and the class itself as public. That should (I think) give you what you want.

like image 108
Paolo Avatar answered Oct 06 '22 20:10

Paolo


Shouldn't an internal constructor solve the issue? That way only your assembly can create instances, but the user can still use instances without restrictions.

like image 35
Marcel Jackwerth Avatar answered Oct 06 '22 19:10

Marcel Jackwerth