Click here to Skip to main content
15,887,881 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Here is a code sample: I don't want to expose the internal sealed class just the interface.

here is what I want to do IDataService id = new IDataService() is it possible or is there a work around?

C#
public interface IDataService
{
    method a
    method b
    method c
    method etc
}

internal sealed class DataService : IDataService
{
    method a
    method b
    method c
    method etc
}

thanks

What I have tried:

The only thing I have tried that works is to change the class to public but that is not an option for me
Posted
Updated 10-Aug-17 6:52am
v2

There is no way to create an object from an interface!
I'm not sure what do you mean by not exposing the class, but your only option is:
C#
IDataService id = new DataService()
 
Share this answer
 
v2
You can't create an instance of an interface.
You define a class which implements the interface. Then create an instance of that class.

// This works
IDataService myService = new DataService();
 
Share this answer
 
Comments
Member 13354128 11-Aug-17 11:51am    
Thanks for the input and this works as long as I make the DataService public but I need it to stay internal To prevent developers from accessing the internal classes and trying to alter them by extending them or deriving off of them. Is there a workaround/back door?

This--> internal sealed class DataService : IDataService
NOT This--> public sealed class DataService : IDataService
cvogt61457 11-Aug-17 13:24pm    
Internal is available within an assembly. It is not visible outside the assembly.
You will need to provide a class (a factory) within the assembly that will give you the IDataService to use outside the assembly.

Assembly1
public interface IDataService
{
}
internal sealed class DataService : IDataService
{
}

Assembly2
// Won't work - DataService is internal
DataService dataService = new DataService();

// Will work
IDataService dataService = factory.GetService();
Kornfeld Eliyahu Peter 12-Aug-17 15:58pm    
The moment your class is sealed no other class can inherit from it, public is irrelevant to that...
If you want to prevent from others to see your code - do some obfuscation...
You have to follow the rules: Interfaces (C# Programming Guide) | Microsoft Docs[^],
Especially:
Quote:
To implement an interface member, the corresponding member of the implementing class must be public, non-static, and have the same name and signature as the interface member.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900