How do you "override" an Internal Class in C#? - c#

There's something I want to customize in the System.Web.Script.Services.ScriptHandlerFactory and other .NET stuff inside an internal class. Unfortunately, it's an internal class. What options do I have when trying to customize a method in this class?

You might find this recent article enlightening. Basically, it says that you can't override anything marked internal, and the source is about as authoritative as it gets. Best you can hope for is an extension method.

The internal keyword signifies that a unit of code (class, method, etc.) is "public" to the assembly it is in, but private to any other assembly.
Because you are not in the same assembly, you cannot do anything. If it wasn't internal you could use the new keyword on the method you're overriding (to hide the original implementation) when extending the class.
In short: you are to be SOL.
The only thing i can think of you could do is write a proxy class, where one of your private fields is the class you'd want to extend and you implement all it's methods and proxy their calls. that way you can still customize output, but you'd have to get your class used, and considering it's marked internal, i'm not sure that's possible without some serious hacking.
using System;
...
using System.Web.Script.Services
namespace MyGreatCompany.ScriptServices
{
public class MyScriptHandlerFactory /* implement all the interfaces */
{
private ScriptHandlerFactory internalFactory;
public MyScriptHandlerFactory()
{
internalFactory = new ScriptHandlerFactory();
}
...
}
}
This could make what you want to accomplish possible, but it won't be pretty.

I believe you can use Reflection to get around the access modifiers on a class, so perhaps you can use Reflection.Emit to generate a type that inherits from an internal type (but NOT the sealed modifier), though I can't find an example of this online.
This certainly works for accessing private members of classes, and probably for inheritance of non-sealed classes. But it doesn't help much if the target methods are not already marked virtual.

It depends on the assembly. This could possibly violate some licensing (although its similar to some sort of static linking), and maybe even make deployment a nightmare, but you could consider:
Decompile and copy the code over to your own project; modify as needed
Recompile/patch the assembly and add an "InternalsVisibleToAttribute"

Related

Should I be using "internal" or "private" instead of "public" for methods that call other methods?

In my C# project I have methods that call other methods like this:
options = ReferenceUtilities.GetMenuStatuses();
In my ReferenceUtilities I have coded:
internal static SelectList GetMenuStatuses()
{
throw new NotImplementedException();
}
But should I be using internal or private? I am not sure of the difference here.
As people have already answered, internal means that the member can be accesed by other code in the same assembly. private means that it can be accessed from other code in the same class.
However, one important point to add:
In Properties/Assemblyinfo.cs, you can add the [assembly: InternalsVisibleTo("something")] statement, that lets you access the internal methods from a different assembly.
This can be extremely useful for unit testing purposes, and is a good reason to sometimes use internal over private.
(There is a huge debate over unit testing internals or not, but it is good to know about the possibility.)
internal means that the member can be accesed by other code in the same assembly. private means that it can be accessed from other code in the same class.
This has nothing to do with whether the method calls other methods.
Internal means that other classes in the same assembly can see the method. Private means only the class where the method is defined can see it. If the method will only ever be called by the class that defines it, use private. Otherwise, use internal. Public should only be used when classes outside the assembly need to call the method directly.
As always, there are exceptions, but this is a good general rule to live by.
Going a bit further, service classes (i.e. methods that exist solely to provide a service or feature) should implement interfaces that define the contract for that service or feature. Other classes should pass around an instance of that interface so that only the interface methods are available.
internal is between assemblies while private is between classes
internal: not visible to code from other assemblies, only visible in this assembly
private: not visible to other classes. only visible in this class
public: visible to other classes or assemblies [for class]

Accessing a private method from another class

I have two repository classes (RepositoryFactory and BaseRepository) implementing different interfaces within the same project. The BaseRepository class has a private method that would be now needed also in the other class, with the same implementation.
Instead of duplicate the method in order to keep it private, I was thinking to a possible alternative, although so far I could not find a good solution since by definition a private method has scope only in its own class.
Using inheritance and change the method to "protected" would also not be an option, since the two classes are not linked semantically. I cannot use a public property giving back the result of the method since the return type is void.
You can use reflection. Here's an example:
MethodInfo privMethod = objInstance.GetType().GetMethod("PrivateMethodName", BindingFlags.NonPublic | BindingFlags.Instance);
privMethod.Invoke(objInstance, new object[] { methodParameters });
It's not possible to do what you want in C#. The closest you can have is internal, which makes the member visible to an entire assembly. It might also be possible to make the two classes private and nested inside another class, but this isn't always appropriate.
Mads Torgersen, who works on C#, has this to say about it:
I've seen a number of proposals trying to grapple with some notion of "class set accessibility." The complication of course is that, unlike existing accessibilities, there is not already a natural group (everyone, assembly, derived classes, single class) to tie it to, so even with another accessibility modifier you still also need syntax (or something) to define the group.
There are several ways to slice it. I haven't seen a proposal that is obviously right, but I think the problem is relevant, and I will take this up with the design team.
(source)
You can, but it looks awkward. This takes advantage of nested classes being able to access private stuff from the containing class. However, even if something is possible doesn't mean you should do it. If you just change the modifier to internal you get the same behavior and since the two classes are coupled together then it makes sense to ship them in the same assembly, so internal modifier is the correct answer.
public class BaseRepository
{
public sealed class RepositoryFactory
{
public static BaseRepository Create()
{
var repo = new BaseRepository();
repo.MethodRequiredByRepositoryFactory();
return repo;
}
}
private void MethodRequiredByRepositoryFactory() { }
}
Reference
Possible by using reflection
Create a console application in Visual Studio.
Add 2 namespaces
2.1. System
2.2. System.Reflection
Now create a class and inside that class create one method that will be private as follows:

Why use a public method in an internal class?

There is a lot of code in one of our projects that looks like this:
internal static class Extensions
{
public static string AddFoo(this string s)
{
if (s == null)
{
return "Foo";
}
return $({s}Foo);
}
}
Is there any explicit reason to do this other than "it is easier to make the type public later?"
I suspect it only matters in very strange edge cases (reflection in Silverlight) or not at all.
UPDATE: This question was the subject of my blog in September 2014. Thanks for the great question!
There is considerable debate on this question even within the compiler team itself.
First off, it's wise to understand the rules. A public member of a class or struct is a member that is accessible to anything that can access the containing type. So a public member of an internal class is effectively internal.
So now, given an internal class, should its members that you wish to access in the assembly be marked as public or internal?
My opinion is: mark such members as public.
I use "public" to mean "this member is not an implementation detail". A protected member is an implementation detail; there is something about it that is going to be needed to make a derived class work. An internal member is an implementation detail; something else internal to this assembly needs the member in order to work correctly. A public member says "this member represents the key, documented functionality provided by this object."
Basically, my attitude is: suppose I decided to make this internal class into a public class. In order to do that, I want to change exactly one thing: the accessibility of the class. If turning an internal class into a public class means that I have to also turn an internal member into a public member, then that member was part of the public surface area of the class, and it should have been public in the first place.
Other people disagree. There is a contingent that says that they want to be able to glance at the declaration of a member and immediately know whether it is going to be called only from internal code.
Unfortunately, that doesn't always work out nicely; for example, an internal class that implements an internal interface still has to have the implementing members marked as public, because they are part of the public surface of the class.
If the class is internal, it doesn't matter from an accessibility standpoint whether you mark a method internal or public. However it is still good to use the type you would use if the class were public.
While some have said that this eases transitions from internal to public. It also serves as part of the description of the method. Internal methods typically are considered unsafe for unfettered access, while public methods are considered to be (mostly) free game.
By using internal or public as you would in a public class, you ensure that you are communicating what style of access is expected, while also easing the work required to make the class public in the future.
I suspect that "it is easier to make the type public later?" is it.
The scoping rules mean that the method will only be visible as internal - so it really doesn't matter whether the methods are marked public or internal.
One possibility that comes to mind is that the class was public and was later changed to internal and the developer didn't bother to change all the method accessibility modifiers.
I often mark my methods in internal classes public instead of internal as a) it doesn't really matter and b) I use internal to indicate that the method is internal on purpose (there is some reason why I don't want to expose this method in a public class. Therefore, if I have an internal method I really have to understand the reason why it's internal before changing it to public whereas if I am dealing with a public method in an internal class I really have to think about why the class is internal as opposed to why each method is internal.
In some cases, it may also be that the internal type implements a public interface which would mean that any methods defined on that interface would still need to be declared as public.
It's the same, the public method will be really marked as internal since it's inside a internal class, but it has an advantaje(as you guested), if you want to mark the class as public, you have to change fewer code.
For the same reason as using public methods in any other class - so that they're public to the outside of the containing type.
Type's access modifier has exactly zero to do with its members' access modifiers. The two decisions are made completely independently.
Just because certain combinations of type and members' modifiers produce seemingly (or as others call it "effectively") the same result doesn't mean they're semantically the same.
Local access modifier of a an entity (as declared in code) and its global effective access level (as evaluated through the chain of containment) are completely different things, too. An open office inside of a locked building is still open, even though you can't really enter it from the street.
Don't think of the end effect. Think of what you need locally, first.
Public's Public: classic situation.
Public's Internal: type is public but you want some semi-legal access in the assembly to do some hacky-wacky stuff.
Internal's Public: you hide the whole type but within the assembly it has a classic public surface
Internal's Internal: I can't think of any real world example. Perhaps something soon to become public's internal?
Internal's Public vs Internal's Internal is a false dilemma. The two have completely different meaning and should be used each in their own set of situations, non-overlapping.
internal says the member can only be accessed from within the same assembly. Other classes in that assembly can access the internal public member, but would not be able to access a private or protected member, internal or not.
I actually struggled with this today. Until now I would have said that methods should all be marked with internal if the class was internal and would have considered anything else simply bad coding or laziness, specially in enterprise development; however, I had to sub class a public class and override one of it's methods:
internal class SslStreamEx : System.Net.Security.SslStream
{
public override void Close()
{
try
{
// Send close_notify manually
}
finally
{
base.Close();
}
}
}
The method MUST be public and it got me thinking that there's really no logical point to setting methods as internal unless they really must be, as Eric Lippert said.
Until now I've never really stopped to think about it, I just accepted it, but after reading Eric's post it really got me thinking and after a lot of deliberating it makes a lot of sense.
There does be a difference.
In our project we have made a lot of classes internal, but we do unit test in another assembly and in our assembly info we used InternalsVisibleTo to allow the UnitTest assembly to call the internal classes.
I've noticed if internal class has an internal constructor we are not able to create instance using Activator.CreateInstance in the unit test assembly for some reason. But if we change the constructor to public but class is still internal, it works fine.
But I guess this is a very rare case (Like Eric said in the original post: Reflection).
I think I have an additional opinion on this. At first, I was wondering about how it makes sense to declare something to public in an internal class. Then I have ended up here, reading that it could be good if you later decide to change the class to public. True. So, a pattern formed in my mind: If it does not change the current behavior, then be permissive, and allow things that does not makes sense (and does not hurt) in the current state of code, but later it would, if you change the declaration of the class.
Like this:
public sealed class MyCurrentlySealedClass
{
protected void MyCurretlyPrivateMethod()
{
}
}
According to the "pattern" I have mentioned above, this should be perfectly fine. It follows the same idea. It behaves as a private method, since you can not inherit the class. But if you delete the sealed constraint, it is still valid: the inherited classes can see this method, which is absolutely what I wanted to achieve. But you get a warning: CS0628, or CA1047. Both of them is about do not declare protected members in a sealed class. Moreover, I have found full agreement, about that it is senseless: 'Protected member in sealed class' warning (a singleton class)
So after this warning and the discussion linked, I have decided to make everything internal or less, in an internal class, because it conforms more that kind of thinking, and we don't mix different "patterns".

When defining a class as internal, do you define what would usually be public fields as internal?

When defining a class as internal, do you define what would usually be public fields as internal? Or do you leave them as public? I have a set of classes with public/private methods that I have decided to set as internal. Now, should I change the class' modifier to internal and let the rest of the methods/properties as they are (public/private) or switch them to (internal/private)?
I don't see a big point in changing it to internal, and if by some reason later I want to set them back to public it's going to give a lot of work to have to put them back to public again.
Any other thoughts on this?
I can't see any reason not to leave them as public, as your class won't be visible to outside assemblies anyway. The only case where I think this might matter is when using reflection over that class.
If I have a class that is internal, I leave the class members as public (or protected/private of course if that's what they were). I find that often I have classes that I hope I can keep internal that I end up having to expose eventually and switching all the appropriate members back to public is annoying.
You defnitely shouldn't change private members to internal as that would make them more accessible. There is no need to change public members to internal since nothing outside of the defining assembly will ever be able to get a reference to an internal class anyway.
I think you should give generally members the same visibility as you would if the Type were itself public.
That is, members that are part of the public API should be public, and members that are special-purpose helpers that should only be visible to "friend" classes should be internal.
This means there will be no changes to member visibility if you ever decide to make the Type public.
More importantly, it also documents your intention - anyone reading your code will be able to identify which (if any) members are intended to be internal.
We use internal keyword for members in internal classes, so that the intention is clear. However it fails if one implicitly implement internal interfaces, where the members have to be defined as public. We dont know why and see this as an accidental mistake in the language specification that we have to live with.
Dig around in Reflector for a bit and you'll see that the BCL itself is wildly inconsistent over this. You'll see many internal classes with public members and many others with internal members. Several classes even mix and match the two with no particular rhyme or reason that I'm able to discern.
There is no "right" answer here, but there are a few things you should consider whenever you need to make a decision on this:
internal members cannot implicitly implement an interface, and explicit implementations are always private. So if you want interface members to be accessible through the class instance (the Dispose method of IDisposable is a common one), they need to be public.
Type visibilities can change. You might decide down the road that an internal class has some valuable functionality that you want to make available to the outside. But if you do, then all public members become accessible by everyone. You should decide in advance if this is what you want.
On the other hand, another reason you might make an internal class public is if you decide that you need to subclass it and that the derived classes should be in a different assembly. In this case, some of your internal members should probably be protected internal instead, otherwise derived classes won't have access to members they might need.
In the end, what it all comes down to is writing code to be read and maintained by other people. The modifier internal can mean two very different things to a maintenance programmer:
That it doesn't seem useful to the outside world, but wouldn't actually be harmful either. A typical example would be a utility class that was whipped up in 5 minutes and doesn't do much validation or error checking. In this case, it's OK for someone to make it public as long as they tighten up the code a little and/or document how to use it properly. Make this assumption explicit by making the members public.
That it's actually not safe for outside consumption; it might manipulate some protected state, leave handles or transactions open, etc. In this case, you really want to make the individual methods internal to make it absolutely clear that nobody else should be using this class, ever.
Choose whichever one is appropriate for your scenario.

Practical uses for the "internal" keyword in C#

Could you please explain what the practical usage is for the internal keyword in C#?
I know that the internal modifier limits access to the current assembly, but when and in which circumstance should I use it?
Utility or helper classes/methods that you would like to access from many other classes within the same assembly, but that you want to ensure code in other assemblies can't access.
From MSDN (via archive.org):
A common use of internal access is in component-based development because it enables a group of components to cooperate in a private manner without being exposed to the rest of the application code. For example, a framework for building graphical user interfaces could provide Control and Form classes that cooperate using members with internal access. Since these members are internal, they are not exposed to code that is using the framework.
You can also use the internal modifier along with the InternalsVisibleTo assembly level attribute to create "friend" assemblies that are granted special access to the target assembly internal classes.
This can be useful for creation of unit testing assemblies that are then allowed to call internal members of the assembly to be tested. Of course no other assemblies are granted this level of access, so when you release your system, encapsulation is maintained.
If Bob needs BigImportantClass then Bob needs to get the people who own project A to sign up to guarantee that BigImportantClass will be written to meet his needs, tested to ensure that it meets his needs, is documented as meeting his needs, and that a process will be put in place to ensure that it will never be changed so as to no longer meet his needs.
If a class is internal then it doesn't have to go through that process, which saves budget for Project A that they can spend on other things.
The point of internal is not that it makes life difficult for Bob. It's that it allows you to control what expensive promises Project A is making about features, lifetime, compatibility, and so on.
Another reason to use internal is if you obfuscate your binaries. The obfuscator knows that it's safe to scramble the class name of any internal classes, while the name of public classes can't be scrambled, because that could break existing references.
If you are writing a DLL that encapsulates a ton of complex functionality into a simple public API, then “internal” is used on the class members which are not to be exposed publicly.
Hiding complexity (a.k.a. encapsulation) is the chief concept of quality software engineering.
The internal keyword is heavily used when you are building a wrapper over non-managed code.
When you have a C/C++ based library that you want to DllImport you can import these functions as static functions of a class, and make they internal, so your user only have access to your wrapper and not the original API so it can't mess with anything. The functions being static you can use they everywhere in the assembly, for the multiple wrapper classes you need.
You can take a look at Mono.Cairo, it's a wrapper around cairo library that uses this approach.
Being driven by "use as strict modifier as you can" rule I use internal everywhere I need to access, say, method from another class until I explicitly need to access it from another assembly.
As assembly interface is usually more narrow than sum of its classes interfaces, there are quite many places I use it.
I find internal to be far overused. you really should not be exposing certain functionailty only to certain classes that you would not to other consumers.
This in my opinion breaks the interface, breaks the abstraction. This is not to say it should never be used, but a better solution is to refactor to a different class or to be used in a different way if possible. However, this may not be always possible.
The reasons it can cause issues is that another developer may be charged with building another class in the same assembly that yours is. Having internals lessens the clarity of the abstraction, and can cause problems if being misused. It would be the same issue as if you made it public. The other class that is being built by the other developer is still a consumer, just like any external class. Class abstraction and encapsulation isnt just for protection for/from external classes, but for any and all classes.
Another problem is that a lot of developers will think they may need to use it elsewhere in the assembly and mark it as internal anyways, even though they dont need it at the time. Another developer then may think its there for the taking. Typically you want to mark private until you have a definative need.
But some of this can be subjective, and I am not saying it should never be used. Just use when needed.
This example contains two files: Assembly1.cs and Assembly2.cs. The first file contains an internal base class, BaseClass. In the second file, an attempt to instantiate BaseClass will produce an error.
// Assembly1.cs
// compile with: /target:library
internal class BaseClass
{
public static int intM = 0;
}
// Assembly1_a.cs
// compile with: /reference:Assembly1.dll
class TestAccess
{
static void Main()
{
BaseClass myBase = new BaseClass(); // CS0122
}
}
In this example, use the same files you used in example 1, and change the accessibility level of BaseClass to public. Also change the accessibility level of the member IntM to internal. In this case, you can instantiate the class, but you cannot access the internal member.
// Assembly2.cs
// compile with: /target:library
public class BaseClass
{
internal static int intM = 0;
}
// Assembly2_a.cs
// compile with: /reference:Assembly1.dll
public class TestAccess
{
static void Main()
{
BaseClass myBase = new BaseClass(); // Ok.
BaseClass.intM = 444; // CS0117
}
}
source: http://msdn.microsoft.com/en-us/library/7c5ka91b(VS.80).aspx
Saw an interesting one the other day, maybe week, on a blog that I can't remember. Basically I can't take credit for this but I thought it might have some useful application.
Say you wanted an abstract class to be seen by another assembly but you don't want someone to be able to inherit from it. Sealed won't work because it's abstract for a reason, other classes in that assembly do inherit from it. Private won't work because you might want to declare a Parent class somewhere in the other assembly.
namespace Base.Assembly
{
public abstract class Parent
{
internal abstract void SomeMethod();
}
//This works just fine since it's in the same assembly.
public class ChildWithin : Parent
{
internal override void SomeMethod()
{
}
}
}
namespace Another.Assembly
{
//Kaboom, because you can't override an internal method
public class ChildOutside : Parent
{
}
public class Test
{
//Just fine
private Parent _parent;
public Test()
{
//Still fine
_parent = new ChildWithin();
}
}
}
As you can see, it effectively allows someone to use the Parent class without being able to inherit from.
When you have methods, classes, etc which need to be accessible within the scope of the current assembly and never outside it.
For example, a DAL may have an ORM but the objects should not be exposed to the business layer all interaction should be done through static methods and passing in the required paramters.
A very interesting use of internal - with internal member of course being limited only to the assembly in which it is declared - is getting "friend" functionality to some degree out of it. A friend member is something that is visible only to certain other assemblies outside of the assembly in which its declared. C# has no built in support for friend, however the CLR does.
You can use InternalsVisibleToAttribute to declare a friend assembly, and all references from within the friend assembly will treat the internal members of your declaring assembly as public within the scope of the friend assembly. A problem with this is that all internal members are visible; you cannot pick and choose.
A good use for InternalsVisibleTo is to expose various internal members to a unit test assembly thus eliminating the needs for complex reflection work arounds to test those members. All internal members being visible isn't so much of a problem, however taking this approach does muck up your class interfaces pretty heavily and can potentially ruin encapsulation within the declaring assembly.
As rule-of-thumb there are two kinds of members:
public surface: visible from an external assembly (public, protected, and internal protected):
caller is not trusted, so parameter validation, method documentation, etc. is needed.
private surface: not visible from an external assembly (private and internal, or internal classes):
caller is generally trusted, so parameter validation, method documentation, etc. may be omitted.
Noise reduction, the less types you expose the more simple your library is.
Tamper proofing / Security is another (although Reflection can win against it).
Internal classes enable you to limit the API of your assembly. This has benefits, like making your API simpler to understand.
Also, if a bug exists in your assembly, there is less of a chance of the fix introducing a breaking change. Without internal classes, you would have to assume that changing any class's public members would be a breaking change. With internal classes, you can assume that modifying their public members only breaks the internal API of the assembly (and any assemblies referenced in the InternalsVisibleTo attribute).
I like having encapsulation at the class level and at the assembly level. There are some who disagree with this, but it's nice to know that the functionality is available.
One use of the internal keyword is to limit access to concrete implementations from the user of your assembly.
If you have a factory or some other central location for constructing objects the user of your assembly need only deal with the public interface or abstract base class.
Also, internal constructors allow you to control where and when an otherwise public class is instantiated.
I have a project which uses LINQ-to-SQL for the data back-end. I have two main namespaces: Biz and Data. The LINQ data model lives in Data and is marked "internal"; the Biz namespace has public classes which wrap around the LINQ data classes.
So there's Data.Client, and Biz.Client; the latter exposes all relevant properties of the data object, e.g.:
private Data.Client _client;
public int Id { get { return _client.Id; } set { _client.Id = value; } }
The Biz objects have a private constructor (to force the use of factory methods), and an internal constructor which looks like this:
internal Client(Data.Client client) {
this._client = client;
}
That can be used by any of the business classes in the library, but the front-end (UI) has no way of directly accessing the data model, ensuring that the business layer always acts as an intermediary.
This is the first time I've really used internal much, and it's proving quite useful.
There are cases when it makes sense to make members of classes internal. One example could be if you want to control how the classes are instantiated; let's say you provide some sort of factory for creating instances of the class. You can make the constructor internal, so that the factory (that resides in the same assembly) can create instances of the class, but code outside of that assembly can't.
However, I can't see any point with making classes or members internal without specific reasons, just as little as it makes sense to make them public, or private without specific reasons.
the only thing i have ever used the internal keyword on is the license-checking code in my product ;-)
How about this one: typically it is recommended that you do not expose a List object to external users of an assembly, rather expose an IEnumerable. But it is lot easier to use a List object inside the assembly, because you get the array syntax, and all other List methods. So, I typically have a internal property exposing a List to be used inside the assembly.
Comments are welcome about this approach.
Keep in mind that any class defined as public will automatically show up in the intellisense when someone looks at your project namespace. From an API perspective, it is important to only show users of your project the classes that they can use. Use the internal keyword to hide things they shouldn't see.
If your Big_Important_Class for Project A is intended for use outside your project, then you should not mark it internal.
However, in many projects, you'll often have classes that are really only intended for use inside a project. For example, you may have a class that holds the arguments to a parameterized thread invocation. In these cases, you should mark them as internal if for no other reason than to protect yourself from an unintended API change down the road.
The idea is that when you are designing a library only the classes that are intended for use from outside (by clients of your library) should be public. This way you can hide classes that
Are likely to change in future releases (if they were public you would break client code)
Are useless to the client and may cause confusion
Are not safe (so improper use could break your library pretty badly)
etc.
If you are developing inhouse solutions than using internal elements is not that important I guess, because usually the clients will have constant contact with you and/or access to the code. They are fairly critical for library developers though.
When you have classes or methods which don't fit cleanly into the Object-Oriented Paradigm, which do dangerous stuff, which need to be called from other classes and methods under your control, and which you don't want to let anyone else use.
public class DangerousClass {
public void SafeMethod() { }
internal void UpdateGlobalStateInSomeBizarreWay() { }
}

Categories

Resources