Internal Interfaces & Classes - c#

I'm refactoring some code I didn't write, that contains business logic and proprietary algorithms I don't want to expose. All the code is currently marked as internal; for testing purposes, and to ensure I don't break existing clients/services, I wanted to switch them to use interfaces, and implement those interfaces.
I've marked my classes as internal and their members as protected internal, and my interfaces as internal, but to use the internal interfaces, I've had to make several of my properties public.
I believe, and with some limited testing, seemed to have proven that only friend assemblies, and classes in my assembly, can use these internal interfaces and classes.
As long as both the class, and interface remain internal, even if some of the methods and the properties are marked public, will they be exposed at all?
It doesn't seem so, but I'm looking for anything I might have missed.

If you mean protected as in a using assembly can't directly use them, then yes, if the interface and class are marked internal, then they won't be visible outside the assembly. Think of the access level on the interfaces and members as being separate locks to get through.
If you can see the interface at its access level, then you can store a reference to it, and then if you can see the properties/methods at their access levels, then you can call/set/get them.
Keep in mind, though, as #phoog points out that protected internal is a bit looser than internal.
All this said, if your internal class implements a public interface, and those properties are part of a public interface as well, they could be visible... But that's really getting obscure...
public interface IVisible
{
string VisibleProperty { get; set; }
}
internal class InvisibleClass : IVisible
{
public string VisibleProperty { get; set; }
}
In the above, you could refer to the class InvisibleClass through an IVisible reference in a different assembly if you could find a way to construct or receive a reference to it (for instance, if it were returned from a factory method inside of the original assembly).
All this aside, if your question is that you want to avoid them from being examined through a decompiler, reflection, etc, that's a different question...

A public member is only as accessible as its type ("Normally, the accessibility of a member is not greater than the accessibility of the type that contains it. However, a public member of an internal class might be accessible from outside the assembly if the member implements interface methods or overrides virtual methods that are defined in a public base class.").
Don't be bitten by the protected internal problem, though: a protected internal member is available to derived classes outside the assembly.
References:
Accessibility levels: http://msdn.microsoft.com/en-us/library/ba0a1yw2.aspx
Access modifiers: http://msdn.microsoft.com/en-us/library/ms173121.aspx

You're right. Since you can't access internal classes from outside (apart from friend assemblies), you can't access any of its methods either, even if they're public.
You could access an internal class from outside it it has a public base class or implements a public interface. But you could only access the public methods in that class that are both in the base class (or interface) and overridden in the sub class (so the method should also be virtual or part of an interface - which also makes it virtual). For this, you'd have to obtain an instance to the class referenced by a super class (or interface) variable.

Related

Why cannot implicitly implement a non-public interface member?

Interface:
interface IMyInterface{
internal int Property {get; set;}
}
Class:
public class MyClass: IMyInterface{
internal int Property {get; set;}
}
Result:
CS8704 Error: MyClass doesnot implement interface member Property.get MyClass cannot implicitly implement a non-public member.
Why I have to implement the interface explicitly?
The simple answer to "why is a language like this" is "because that's how the language designers specified it".
Now, why did they design it that way? Some of the official notes I found were these. It seems the main question was about what kind of access the implementor must have:
Would we allow non-public interface members to be implemented implicitly? If so, what is required of the accessibility of the implementing method? Some options:
Must be public
Must be the exact same accessibility
Must be at least as accessible
They decided:
For now, let's simply not allow it. Only public interface members can be implicitly implemented (and only by public members).
The "for now" never changed, so as of C# 8 an interface can have non-public virtual members but a class may only implement them explicitly.
I can speculate on a couple of reasons they may have decided against implicit overrides like this:
Non-public virtual methods in interfaces may have been considered a "rare" feature (after all, aren't interfaces supposed to document the public behavior of a class?), not worth putting a lot of resources into in terms of the semantics of implicit overrides.
Unlike with method overridding in class-to-class inheritance, an class method implementing an interface method doesn't use the override keyword. It might have been considered confusing to see a protected and/or internal method and not realize that it's fulfilling an interface contract. (Public methods are presumably considered exempt from this concern because that's the way they've always worked, and public methods are part of the class' public contract anyway so modifying / removing them would already be cause the reader to think about other parts of code that depend on it.)
Interfaces can only override other interface methods explicitly, possibly again because allowing interface-to-interface implicit implementation would be too expensive for the compiler and tooling teams and too confusing for C# users. (Especially since interface-to-interface inheritance is multiple-inheritance.) Since both this and non-public interface methods were introduced in general in C# 8, it may have made sense to make the two features match syntactically.
See also the notes on this question in the default interface method proposal.
Interface members don't have scopes like public or internal. What you have here is a default interface implementation.
So you need to remove the scope on the interface:
interface IMyInterface{
int Property {get; set;}
}
The internal property forces the implementation to be explicit such that the internal members of the interfaces will remain internal to the assembly.
It helps you to keep implementations internal (to an assembly) so that you can update code without breaking changes e.g. renaming the property.
interface IMyInterface
{
internal int Property { get; set; }
}
public class MyClass : IMyInterface
{
int IMyInterface.Property { get; set; }
}

If I declare an internal class, what the default access level of internal members be?

I'm building a DLL with some basic functions. Long story short, I'm making a few static classes for the use by devs. These classes use some other classes that do the dirty work, which I marked as internal because I don't want people to access them.
The question is: If I declare a class as internal, what the access level of his members will be?
I'll have to mark as internal all of its members or they are automatically labeled as internal too?
It's a good 2 hours I'm googling and searching in stackoverflow and I'm struggling to find a clear and straight answer which doesn't include 1000 speculations, technical not-so-probable hypotesis and useless decorations...
MSDN is confusing as usual (never found a clear answer on msdn).
From what I can read here http://msdn.microsoft.com/en-us/library/ms173121.aspx I guess that no matter how you set a class access level, all his members will be private (methods, variables and so on).
Help, I don't know
The question is: If I declare a class as internal, what the access
level of his members will be?
The default will be private. If anything else, then it depends. If they are anything other than public, then the access modifier applies as described on MSDN (e.g. not visible outside of the assembly).
However, in the link you posted, there is one gotcha which applies to non-static classes:
Normally, the accessibility of a member is not greater than the
accessibility of the type that contains it. However, a public member
of an internal class might be accessible from outside the assembly if
the member implements interface methods or overrides virtual methods
that are defined in a public base class.
In relation to the last paragraph, since static classes cannot implement interfaces or inherit other classes then you can rest assured. As long you declare your static class internal, the members will not be available in other assemblies (unless your devs use reflection).
To exemplify how it does work for non-static classes:
Assembly 1
public interface ISomePublicInterface
{
int GetValue();
}
internal class InternalClass : ISomePublicInterface
{
public int GetValue()
{
return 100;
}
}
public static class SomeFactory
{
public static ISomePublicInterface GetInternalInstanceAsInterface()
{
return new InternalClass();
}
}
Assembly 2
ISomePublicInterface val = SomeFactory.GetInternalInstanceAsInterface();
Console.WriteLine(val.GetValue()); //-->> Calls public method in internal class
Console.WriteLine(val.GetType());
Guess what the output is?
Assembly1.InternalClass
So, now you have access to the type outside of the assembly and via reflection someone could call other internal methods (it's not the only way to get it).
From MSDN only
The access level for class members and struct members, including
nested classes and structs, is private by default.
interfaces default to internal access.
Hope this table helps:
Members of Default member accessibility
---------- ----------------------------
enum public
class private
interface public
struct private
Also check this MSDN
Private unless otherwise stated. However, public will have same result as internal.
If you later promote a class from internal to public, then creating public class objects will become visible, whilst internally scoped methods will stay internal.
You might want to consider behaviour in case your class scope gets updated.
Another stack overflow question.
If u Declare any class as "internal" then its means you can access this class in same assembly. But what kind of access specifier you use for class member is decide they are accessible are not in different class in same assembly.
All the members of internal class would be internal and will be accessible with in the same assembly and will not be outside neither class nor members.
If you want to access class in other assemblies, make the class public and member you don't want to be accessed outside assembly make them internal.

Abstract Class Design: Why not define public constructores?

Look here (Abstract Class Design): http://msdn.microsoft.com/en-us/library/ms229047.aspx
It says:
(1) Do not define public or protected internal (Protected Friend in Visual Basic) constructors in abstract types.
In C#, we are not able to instantiate an abstract class. So, does it still matter to define public constructors for abstract classes in C# ? Or not writing public constructors for abstract classes because of semantic meaning?
It also says:
(2) Do define a protected or an internal constructor in abstract classes.
Define internal constructors ?? In (1), it tells us that not defining internal protected constructors is because that "Constructors with public or protected internal visibility are for types that can be instantiated". Doesn't defining internal constructors for abstract classes break the rules in (1) ?
Thanks in advance. :)
Let's look at each of the cases.
Recommended:
protected - The most obvious case - all subclasses can call the constructor, irrespective of which assembly they reside in (as long as the the abstract base-class itself is visible to them).
internal - Useful when you want the abstract type to be publicly visible, but not publicly inheritable. In this case, you would want to make all of the non-private constructors internal. Only subclasses within the same assembly as the abstract base-class would be able to call the constructors - effectively, only they would be able to inherit. Another use-case would be if you wanted a 'special' constructor that should only be visible to same-assembly subclasses.
private - Used mainly for 'dirty-work' constructors that are targeted by other constructors of the abstract class when it uses constructor-chaining. The only other use, when all the constructors are private, is to only allow subclassing by nested classes, which do have access to private members of the containing-type.
Not recommended:
public - Not useful, behaves identically to protected. Only subclasses can call the constructor anyway, since the base-class is abstract.
protected internal - This too is no different from protected. The protected internal accessibility level means protected OR internal, not protected AND internal. However, the internal modifier here serves no purpose - it doesn't prevent subclasses residing outside the assembly from calling the constructor (assuming the abstract base-class is public) since they can rely on protected access, nor does it allow same-assembly types that are not subclasses from calling it (the type is abstract).
The key point here is that every non-private constructor in an abstract class is already at best protected. The vanilla internal-modifier strengthens restrictions on who can call the constructor. public and protected internal don't accomplish anything because they appear to weaken restrictions, but don't really succeed in doing so.
n C#, we are not able to instantiate an abstract class. So, does it still matter to define public constructors for abstract classes in C# ? Or not writing public constructors for abstract classes is because of the semantic meaning?
Exactly. You don't want the user to see an accessible constructor, but when they call it, they get a compile error.
Define internal constructors ?? In (1), it tells us that not defining internal protected constructors is because that "Constructors with public or protected internal visibility are for types that can be instantiated". Doesn't defining internal constructors for abstract classes break the rules in (1) ?
I believe rule 1 is about public and protected internal rule 2 is about protected and internal. So there's no intersection between the two.
Years passed. I think I have better understanding of this question now. So I would like to add some more input besides Ani's excellent answer.
In C#, we are not able to instantiate an abstract class. So, does it
still matter to define public constructors for abstract classes in C#
?
It doesn't matter to the compiler, but it does matter to code readers. Public constructors in abstract types is misleading to code readers (they might think they can be instantiated).
Define internal constructors ?? In (1), it tells us that not defining
internal protected constructors is because that "Constructors with
public or protected internal visibility are for types that can be
instantiated". Doesn't defining internal constructors for abstract
classes break the rules in (1) ?
If we want the abstract class to be inheritable only by subclasses within the same assembly, obviously we cannot use protected (otherwise it can be inherited outside the assembly). Now we have some options to choose:
public - As mentioned above, public is misleading to code readers. Don't use it.
private - We want the abstract class to be inheritable by subclasses within the same assembly, not just by nested subclasses, so private won't work.
protected internal - We'll never need it because it's no different from protected.
internal - It is misleading to code readers, but we have no other choice. I would think it a trade-off.

What's the difference between an abstract class and a static one?

Neither is instantiable. What are the differences, and in what situations might you use one or the other?
static indicates the class can only have static members and you cannot create an instance of it. This is used for stateless functionality (for example a type that just defines extension methods, or utility methods). You can also declare a member static on a non-static class. This allows you to attach functionality to a type without having to instantiate it.
Here's more detail on using static members and classes.
abstracts define the basic structure and functionality shared by all derivative types, but cannot be used by themselves. Think of them as, I suppose, a blue print and a contract. This is a core concept for OOP.
Here's more detail on using abstracts.
Here is a short summary:
A static class can only contain static members (it is just a container for methods that do not logically belong to an instance of any standard class)
An abstract class can contain all usual kinds of members (static, abstract and also instance)
The key difference is that you can inherit from an abstract class, but you cannot inherit from a static class. Technically speaking, the .NET runtime doesn't have any notion of static classes, so the C# compiler compiles them as classes that are both abstract and sealed (meaning that you cannot inherit from them).
So, static classes are abstract classes that are also sealed (although this is not the usual way to look at the problem if you are C# programmer) and contain only static members (which is enforced by the C# compiler).
An abstract class is intended to be used as a base of a class inheritance hierarchy. A static class cannot be the base of a class inheritance hierarchy.
A static class is intended for singleton state or stateless functionality. An abstract class is not suitable for singleton functionality, because, even though it may contain static methods and fields as a static class does, it cannot forbid inheritance, so the singleton use may be defeated by subclasses. Or, at the very least, it would be confusing to other programmers, because its definition would communicate an intent that is different from its actual intended use.
The superficial similarity between abstract and static classes is only in the fact that neither may be instantiated. Beyond that, they are completely different animals with completely different use cases.
The CLR has no notion of static classes, it is specific to C#. The compiler implements it by slick use of CLR attributes for a class: it declares it abstract and sealed. That prevents any language from instantiating such a class. This is what it looks like when you run Ildasm:
.class public abstract auto ansi sealed beforefieldinit ConsoleApplication1.Test
extends [mscorlib]System.Object
{
}
Making it sealed is very much the point of a static class, it is used as a container for static methods and fields. Which makes them act like global variables and functions like you have in languages like C or Pascal.
An abstract class is very much the opposite, it is designed to be derived from. A abstract class that has all of its member abstract acts like an interface. C# has a keyword for that, making static class and interface the exact opposites.
Abstract classes get instantiated indirectly via derived classes. They provide common behaviour and instance state, but signal that more is required and must be provided by derived concrete classes. For example, Transform might be an abstract class: it declares a common Apply(Shape) method, but no implementation of that method. Concrete derived classes like Rotation or Translation will implement that method, and those classes can be instantiated.
Static classes cannot be instantiated, and any state is at the class level rather than the instance level. They are typically used to define utility methods where there is no state associated with the methods. Transform couldn't be a static class, because the concrete derived classes need per-instance state (e.g. Rotation needs a per-instance Angle, because different Rotation transforms could be by different angles).
Abstract classes are intended to be used as base classes; they cannot have direct instances. Instead, you have to derive subclasses, which provide the what was (usually intentionally) left out in the abstract base class.
Example: consider you have a complex application, where users may log-in to. Various authentication mechanisms should be usable, say, LDAP, NTLM, you name it. One way to model a "user" or "principal" in such a context would be to collect, what is common across all those mechanisms, into an abstract base class, and leave "gaps" (abstract methods) where the actual implementations come into play:
abstract class Authenticator {
protected Dictionary<string,User> userCache;
...
public User LoadUser(string name) {
User user;
if( userCache.TryGet(name, out user) ) return user;
else {
user = LoadFromStore(name);
userCache.Add(name, user);
return user;
}
}
protected abstract User LoadFromStore(string name);
}
Here, caching of users is a common concern, modelled in the base case, whereas the actual retreival is left for a subclass to provide.
Static class are a different matter alltogether. They are essentially a place to keep your utility functions:
static class StrUtil {
public static string TrimWhitespace(string str) {
...
}
}
Think of them as some kind of special namespace, which can only contain static members. Basically, a place to put functions.
Abstract Class (Base class):
Enables other classes to inherit from this class (one class acquires the properties (methods and fields) of another) , but forbids to instantiate i.e we cannot have objects of this class.
http://csharp.net-tutorials.com/classes/abstract-classes
Static Class:
This class cannot be instantiated. Also this class cannot be inherited. To access methods of this class, you can directly use classname.method.
https://social.technet.microsoft.com/wiki/contents/articles/21028.difference-between-static-class-sealed-class-and-abstract-class-in-c.aspx
Abstract class main purpose is to define one or more abstract method(s).
Any class extending Abstract class will implement the abstract method or else its also need to be declared as "Abstract".
But, its also possible to declare a class as "Abstract" without implementing any abstract method(s) in it. See the sample below.
public abstract class AbstractTest {
public void abcd(){}
public static void main(String[] args) {
System.out.print("hi...");
}
}
Only inner class can be declared as "Static", see the code below.
Upper/encapsulating class can't be declared as "Static".
It can be accessed by using Upper/encapsulating class variable.Static-inner-classname i.e same as any static method invocation using class name.
public class StaticTest {
public static void main(String ag[]){
System.out.println("hello...1");
StaticTest.StaticTest2.meth2();
}
public static class StaticTest2 {
public static void meth2(){
System.out.print("hello...2");
}
}
}
Main difference between the two is extensibility.
CLR marks all 'static' classes as 'abstract & sealed' behind the scene (i.e., they cannot be inherited hence cannot be extended) and .NET Framework CLR loads them automatically when containing program or namespace is loaded. This gives performance gain on runtime.
Philosophy behind 'abstract' classes is capitalizing all common features of all extended classes in one place.
Hope it helps.

internal abstract methods. Why would anyone have them?

I was doing some code review today and came across an old code written by some developer. It goes something like this
public abstract class BaseControl
{
internal abstract void DoSomething();
}
If you have a derived class within the same assembly, it would work
public class DerivedControl : BaseControl
{
internal override void DoSomething()
{
}
}
But deriving the base class in a different assembly would give compile time error
DerivedControl does not implement inherited abstract member 'BaseControl.DoSomething()
That got me thinking. Why would anyone declare a method as internal abstract ?
The original programmer wanted to make a derived control available to client code. But prevent the client from inheriting and messing with the virtual method. That's not a bad idea, it is usually easy to break a base class by overriding a method and doing something like forgetting to call the base class method.
One obvious case is where the method receives or returns an internal type. For example, the core methods of the WPF Transform classes process some internal interop types, which WPF doesn't expose as part of its public API. Because the signature includes internal types, the method can't be public or protected. And yet clearly it's appropriate (necessary!) for the various Transform classes to work polymorphically. Therefore the base methods in Transform/GeneralTransform have to be internal.
Another, but related reason is to prevent external derivation. After all, the WPF architects could have exposed a "safe" version of the internal interop types in a protected abstract method, so that users could create their own Transform classes. They didn't because they didn't want to have to cope with the ways that people might use that capability, e.g. creating non-affine transforms. Allowing external derivation would have made the job of other classes in WPF hugely more complex, so the architects decided to allow only "approved" derived classes by making an abstract method internal.
My initial reaction was that there is no good reason, if you want to prevent external inheritance then you should mark the class internal. But that means that the class is totally hidden to other assemblies.
I suppose this method prevents external inheritance while retaining visibility.
By defining a method as internal abstract you want to make sure that only the class in the same assembly can have its implementation for your method.
now if you distribute a dll of it this will avoid the client to inherit and mesup the implementation.

Categories