I think it is by design and there is nothing can be done about it, but I found it interesting.
I needed to create a concreate class based on third-party abstract base class. As always, I told Visual Studio to implement abstract base class, which it did, but the code didn't compile complaining about missing getter. However, event after adding getter manualy, the code still didn't compile. It turned out that this getter is internal. Funny thing about internal property is that it's not shown in metadata (View Definition). Vendor will make it protected in the next release, but at the time being, unless I'm missing some other way, there is nothing I can do about it, right?
-Stan
That's correct.
In fact, we basically do the same thing in Noda Time where we want to expose a type (CalendarSystem) so that clients can pass calendars around - but all the actual interaction is internal to the library, using other internal types. What you've got as a problem in your situation is actually a blessing in ours, as it means we can keep more of the implementation internal and hidden :)
It's harder to do the same thing with interfaces...
Related
I'm trying to find out if there's a way to stop functions/methods from being added (EDIT: by other developers) to a class for the case where the object is a Model or DTO which should not contain methods (to prevent 'abuse' of the Models/DTOs by others, who may try and add 'helper' methods etc).
Is there any way to achieve this?
Use reflection and write a unit test that fails if a model-class has methods.
Mark all you model classes with a custom attribute. Then make a unit test that uses reflection to load a given assembly, iterate all classes in that assembly and check that classes marked with the model attribute does not have methods. This should be fairly straight forward using reflection.
I believe you are trying to solve a procedural issue with code where you should be using communication.
Your colleagues (i assume) are operating on the code files with 'full trust' privileges. If they break that privilege you should open a dialogue. Use the change as an opportunity to educate them on the intended design. Perhaps they are correct and you will be educated!
I suggest simply making the intended design obvious in the class name and with a comment stating the intended nature. Perhaps quote the design document(s) that informed the class.
You cannot hinder anyone with full write-access to your code-base to do so. The only two things you may do to avoid it are create some CodeAnalysis-rule for FXCop as mentioned by Christian.K in the comments or by writing your DTO-class so that it is undoubtly a DTO that should not have any methods by using a unambigious name for the class and if this is not enough provide some code-comments that notifies the coder to do not so.
However you may need some kind of method if using collections e.g. where you will need some kind of comparision if two instances of your DTO are equal, so you have to provide at least an Equals- and GetHashCode-method.
You don't need to use a struct to prevent additions to a class. You can use the sealed keyword
public sealed class MyDTOObject { ... }
Now, you can not inherent a class and also prevent inheritance (which is essentially what you're asking). The very fact of inheriting MyDTOObject is creating a new class which is based off of not equal to, or restricted, or defined in any way by the implementation of MyDTOObject.
You can use an abstract class, to force derived classes to implement certain methods, but not the other way around.
If you want to prevent others from deriving from your class and implementing helper methods, you must use the sealed keyword, or mark the class internal.
You may prevent the class being extended or inherited by marking it final that way nobody would be able to extend your class and hence not being able to add any behavior. But stop and ask yourself whether you want to do that or not, because then you'd be signing an invisible contract that everything ever required by the class is written in the class and this class needs no further addition.
To be clear, I was talking in Java context.
Situation:
I implement an interface implicit and remove a property on the interface (later).
There is no warning that this property should be removed on the implementation class.
I know I could implement the interface explicitly, but I would try to go around that.
EDIT: (added a question)
How can I be notified/warned/... that I maybe no longer need the member in the implementing class?
There is no way the compiler can give you such a warning in C#. It would somehow need to have knowledge of past versions of the interface to know what method/property was removed and therefore identify possible candidates for removal.
And answering your commentary, you can not make the compiler / refactoring tool decide if any given method is a candidate simply based on the #region its defined in. There is absolutetly nothing that enforces any given method to be defined in any given region, its just visual sugar so refactoring based on regions would be completely unsafe.
Sometimes verbose languages do have advantages, and in this case VB with the implements keyword would make this a compile time error. In C#, you have to use explicitly implemented interfaces which is not a bad option at all. Read here for more details.
This question already has answers here:
Instantiating Internal class with private constructor
(5 answers)
Closed 7 years ago.
I'm either googling the wrong thing or trying to head down the completely wrong path (most likely)... but now I'm curious so I thought I'd ask.
Long story short, I'm trying to tap into the underlying "API" framework of Microsoft's Message Analyzer tool for a custom application. I say "API" because there is no formal support for an API, no documentation, and there won't be any in the near future, if ever (so says Paul at Microsoft anyway). So instead I've been using the IL DASM tool to poke around some of the Message Analyzer and PowerShell .dlls to try to get an understanding of how this stuff works; the ultimate goal of course is to use MA's .dlls and drivers to do what I want for the custom app. I'm looking at Microsoft.Protocols.Tools.PowerShell.dll, which has a class (Microsoft.Protocols.Tools.PowerShell.PpkTraceSession) that I'm trying to instantiate:
However, if you look right below it, it says something about the class being private (it's cut off in the picture, but the class does implement IPpkTraceSession and IPpkTraceSessionEx). Sure enough, when I reference this .dll in some C# code and try to instantiate an object, I get a compile error saying its inaccessible due to its protection level:
Windows PowerShell has no problem at all creating one of these objects. It just so happens the printout seen below matches all the properties (not seen in the first picture) of the PpkTraceSession class, so I know Windows PowerShell is working some magic to create an object of that class,, I just can't figure out how since apparently this class is private.
So my question,, what's going on here? I've poked around in a lot of the classes shown in the IL DASM output, and there are a surprising number of them that appear to be private. Maybe it's just my bad practice, but I've rarely if ever used or seen many private classes. It's my understanding they have to be nested in other classes to be of any particular use. If PpkTraceSession is nested in another class, that's not clear from the IL DASM output at all. You may see the IPpkTraceSession(Ex) interfaces above,, if there's a way to access the class properties using those I haven't figured it out yet. Is there anyway to instantiate an object of this class, or am I going about this all wrong?
This might be close to a duplicate, but not quite I don't think. Any help is much appreciated! I clearly don't know much about Windows programming.
yano
EDIT:::::
Just to tie off all the loose ends (in case somebody else makes my mistake), I discovered the source of my confusion a couple of days ago. All the classes indicated as "private" by the IL DASM tool are actually "internal" classes, meaning that they're meant to be visible only within their own assembly. That was my missing piece, I couldn't understand where all these private classes were coming from when C# won't even let you compile a standalone private class (it must be nested within another class). I should've done some more research on IL DASM before I posted a question, but it didn't even occur to me; I thought private meant private. It's my observation that IL DASM does make a distinction between private/internal classes and nested private classes. This issue has also already been addressed here: When I declare a class as internal, why does the IL show it as private? . Thanks for the help everyone!
I suspect that what you are seeing is that other classes, probably deep inside the PowerShell plumbing, might expose some of the properties of the PpkTraceSession class. You might be able to find them by inspecting the intermediate language of the public classes exposed by the same dll THAT contains the private PpkTraceSession class. However, I suspect that you are wasting your time, and will not find a way to use those classes in your own code.
They are marked private because Microsoft has no intention of supporting them, and their behavior might change without notice. That isn't a problem within the PowerShell team, which has access to them, most likely through other private classes. So, if they need to change the way one of those classes behaves, they can do it, and the affected audience is small and easily reachable.
Speaking as a developer, I can think of a host of reasons that Microsoft might not want to support it, such as that it is very fussy, or that doing so would involve disclosing proprietary or patented technology that they have a legal right to keep secret.
Perhaps you could start a campaign to make them public, but you'll need to make a really good case, and convince a lot of other people, preferably people who already pay Microsoft a lot of money, to get behind you.
Im currently working on a c# project that uses another .net library. This library does (amongst other things) parse a sequence into a tree. All items are of some type that inherits from the abstract class Sequence. I needed to alter the behaviour slightly and subclassed Sequence myself (lets call it MySequence). After the tree was created, I could replace some tree nodes with objects of my own class.
Now, a new version of the library was published, and a Copy function with the following signature was introduced:
internal abstract Sequence Copy();
I tried to adopt my code to the new version and override it, but whatever I am doing, I get the two errors:
MySequence does not implement inherited abstract member 'Sequence.Copy()'
and:
MySequence.Copy()': no suitable method found to override
This makes sense, since it is abstract (--> it must be overwritten) and internal (--> it can not be overwritten, due to hidden visibility from outside the assembly)
So, the problem is, I understand why this is happening, but dont know what to do against it. It is crucial for my project to subclass Sequence.
And what I also dont understand is, why the internal abstract modfier is allowed in the first place as it basically permits any subclassing of the whole class from outside the assembly!?
Is there any way to solve this? Via reflection or something?
Thanks in advance!
Basically, you are out of luck without altering the library. There may be a subclass of Sequence that does implement Copy, which you can derive from in the new version. But it is likely that the Copy method is need in other parts of the library to create clones.
This modifier means that the class can only be inherited in the assembly that defined it.
There is no way around that.
If a library has a type with a member with the modifiers internal abstract, I conclude that the developers of that library didn't want anyone to derive their own type from that type. You cannot work around this.
You can consider whether this was done deliberately. You should ask the publishers. It might be a mistake, in which case the publishers will probably issue a fix. If it is done deliberately, you should come up with an alternative solution without deriving from that type.
EDIT: Or perhaps they intended for you to derive only from derived types in the same assembly that already implement that member.
I'm a pretty new C# and .NET developer. I recently created an MMC snapin using C# and was gratified by how easy it was to do, especially after hearing a lot of horror stories by some other developers in my organisation about how hard it is to do in C++.
I pretty much went through the whole project at some point and made every instance of the "public" keyword to "internal", except as required by the runtime in order to run the snapin. What is your feeling on this, should you generally make classes and methods public or internal?
I believe in blackboxes where possible. As a programmer, I want a well defined blackbox which I can easily drop into my systems, and have it work. I give it values, call the appropriate methods, and then get my results back out of it.
To that end, give me only the functionality that the class needs to expose to work.
Consider an elevator. To get it to go to a floor, I push a button. That's the public interface to the black box which activates all the functions needed to get the elevator to the desired floor.
What you did is exactly what you should do; give your classes the most minimal visibility you can. Heck, if you want to really go whole hog, you can make everything internal (at most) and use the InternalsVisibleTo attribute, so that you can separate your functionality but still not expose it to the unknown outside world.
The only reason to make things public is that you're packaging your project in several DLLs and/or EXEs and (for whatever reason) you don't care to use InternalsVisibleTo, or you're creating a library for use by third parties. But even in a library for use by third parties, you should try to reduce the "surface area" wherever possible; the more classes you have available, the more confusing your library will be.
In C#, one good way to ensure you're using the minimum visibility possible is to leave off the visibility modifiers until you need them. Everything in C# defaults to the least visibility possible: internal for classes, and private for class members and inner classes.
I think you should err on the side of internal classes and members. You can always increase an item's visibility but decreasing it can cause problems. This is especially true if you are building a framework for others.
You do need to be careful though not to hide useful functionality from your users. There are many useful methods in the .NET BCL that cannot be used without resorting to reflection. However, by hiding these methods, the surface area of what has to be tested and maintained is reduced.
I prefer to avoid marking classes as public unless I explicitly want my customer to consume them, and I am prepared to support them.
Instead of marking a class as internal, I leave the accessibility blank. This way, public stands out to the eye as something notable. (The exception, of course, is nested classes, which have to be marked if they are to be visible even in the same assembly.)
Most classes should be internal, but most non-private members should be public.
The question you should ask about a member is "if the class were made public would I want to member the member to be exposed?". The answer is usually "yes (so public)" because classes without any accessible members are not much use!
internal members do have a role; they are 'back-door access' meant only for close relatives that live in the same assembly.
Even if your class remains internal, it is nice to see which are front-door members and which are back-door. And if you ever change it to public you are not going to have to go back and think about which are which.
Is there any reason you need to use Internal instead of Private? You do realise that Internal has assembly level scope. In other words Internal classes/members are accessible to all classes in a multi-class assembly.
As some other answers have said, in general go for the highest level of encapsulation as possible (ie private) unless you actually need internal/protected/public.
I found a problem using internal classes as much as possible. You cannot have methods, properties, fields, etc of that type (or parameter type or return type) more visible than internal. This leads to have constructors that are internal, as well as properties. This shouldn't be a problem, but as a matter of fact, when using Visual Studio and the xaml designer, there are problems. False positive errors are detected by the designer due to the fact that the methods are not public, user control properties seems not visible to the designer. I don't know if others have already fallen on such issues...
You should try to make them only as visible as possible, but as stated by Mike above, this causes problems with UserControls and using the VS Designer with those controls on forms or other UserControls.
So as a general rule, keep all classes and UserControls that you aren't adding using the Designer only as visible as they need to be. But if you are creating a UserControl that you want to use in the Designer (even if that's within the same assembly), you will need to make sure that the UserControl class, its default constructor, and any properties and events, are made public for the designer to work with it.
I had a problem recently where the designer would keep removing the this.myControl = new MyControl() line from the InitializeComponent() method because the UserControl MyControl was marked as internal along with its constructor.
It's really a bug I think because even if they are marked as internal they still show up in the Toolbox to add in the Designer, either Microsoft needs to only show public controls with public constructors, or they need to make it work with internal controls as well.
You should tend toward exposing as little as possible to other classes, and think carefully about what you do expose and why.
It depends on how much control you have over code that consumes it. In my Java development, I make all my stuff public final by default because getters are annoying. However, I also have the luxury of being able to change anything in my codebase whenever I want. In the past, when I've had to release code to consumers, I've always used private variables and getters.
I like to expose things as little as possible. Private, protected, internal, public: give classes, variables, properties, and functions the least amount of visibility they need for everything to still work.
I'll bump something's visibility up that chain toward public only when there's a good reason to.
I completely disagree with the answers so far. I feel that internal is a horrid idea, preventing another assembly from inheriting your types, or even using your internal types should the need for a workaround come about.
Today, I had to use reflection in order to get to the internals of a System.Data.DataTable (I have to build a datatable lightning fast, without all of its checks), and I had to use reflection, since not a single type was available to me; they were all marked as internal.
by default class is created as internal in c#:
internal means: Access is limited to the current assembly.
see
http://msdn.microsoft.com/en-us/library/0b0thckt.aspx
Good Article the defaults scope is internal:
http://www.c-sharpcorner.com/UploadFile/84c85b/default-scope-of-a-C-Sharp-class/
Do not choose a "default". Pick what best fits the visibility needs for that particular class. When you choose a new class in Visual Studio, the template is created as:
class Class1
{
}
Which is private (since no scope is specified). It is up to you to specify scope for the class (or leave as private). There should be a reason to expose the class.