Related
just finished one of my projects and about to start another. This is never taught in my university so i dont even know if it exists. Lets say for example you have the code...
MessageBox.Show("Hi");
Now i know i can call it in Form1.
I also know i can call it in another form providing it is in a public class / void or something?
My question is, is there a library system where i can add 30-40 code snippits each to do their own job. So when i want to update sql or run calculations i just call a code file from a library?
Sorry if im missing something obvious google is driving me insane, i know what i want to ask, just not how to ask it! Hope you understand my question..
Thanks, Regards..
Of course. In your solution in Visual Studio you can add a Class Library project and fill it with all of the re-usable code that you want. Then any project in the solution can reference it by adding a Project Reference to that project.
Note that it's very easy to go overboard on something like this. Take, for example, your example:
MessageBox.Show("Hi");
The MessageBox class is tightly coupled to the user interface. So it belongs in the user interface objects. (The forms in this case.) This is because if you try to use it in your class library then you would need to add user interface libraries to that class library, making it more tightly coupled with that specific user interface implementation. This makes the class library much less portable and less re-usable because it can only be used by projects of that same user interface technology. (Can't be used by web projects, for example.)
So you'll want to think about each common utility that you encapsulate into its own re-usable code. Does it belong in the UI, in the business objects, in the data access, etc.? If it's tightly coupled with a specific periphery technology (user interface technology, data access technology, etc.) then it probably belongs there.
One approach to this would be to have multiple "common utilities" libraries. Using a contrived naming scheme, a larger enterprise domain solution might have projects like this:
Domain.BusinessLogic (class library, referenced by everything)
Application.Forms.AdminPanel (forms application)
Application.Forms.OperationsPanel (forms application)
Application.Forms.Common (class library, referenced by other Forms apps)
Application.Web.PublicWebsite (web application)
Application.Web.Common (class library, referenced by other Web apps)
Infrastructure.DataAccess.SQLServer (class library, dependency-injected into the Domain)
Infrastructure.Vendor.SomeService (class library, dependency-injected into the Domain)
etc.
So you have a core business logic project, which contains anything that's universal to the entire business domain in which you're working. It should have no dependencies. (Not rely on user interfaces, databases, frameworks, etc.) Then you have applications of various technologies, into which are mixed class libraries which have application-coupled common functionality. And finally you have the other periphery of the domain, the back-end dependencies. These could be your data access layer, integrations into 3rd party systems and services, etc.
As any given piece of functionality is abstracted into a common utility to reduce duplication and increase re-use, take care to keep your code-coupling low so the "common utilities" aren't tightly bound to "uncommon dependencies." All too often in the industry there's an increase in tight coupling with code re-use. (See the Single Responsibility Principle.) So exercise good judgement to avoid that.
There's nothing inherently wrong with writing the same piece of code ("same" by keystrokes alone, not necessarily by conceptual purpose) more than once if it serves more than one responsibility and those responsibilities should not be mixed.
It sounds like you want to use static methods. Group your routines by what they do, and put them in a static class, .e.g
internal static class Utility
{
public static void Method1(int whatever)
{
// do stuff
}
public static void Method2(string another)
{
// do other stuff
}
}
You can then call them like:
Utility.Method1(7);
Utility.Method2("thingy");
The simple solution is create a new project and select the "Class Library" option. This will create a class which is compiled into a DLL (dynamically linked library). Everywhere you want to use this common code you add can add a reference to the assembly, then in the specific files you use it, you'll have to add a using statement for it.
If you're required to turn in multiple projects you could put all of them under a single solution. If you right click the solution and select the properties option for the drop down menu it will open a new window with a "Configuration Properties" option in the left nav bar. Select it, then you can specify build dependencies. So if you have projects A and B which use methods in project C (the class library) then you can set that as a build dependency meaning whenever you build project A, B or the solution as a whole, it will first build project C.
This is commonly how enterprise software is structured; some dll's or exe's that are the application level code, then many other projects which build common code that is often shared by multiple projects. All of this is usually put under the umbrella of a single solution.
If you go this route there are more details (like which exe runs by default when you debug) that I can update with. It's probably nothing you'll be taught in university but you'll most likely see as soon as you start your first job.
With C++, I can have one class definition in a header file, and have a multiple implementation files by including the header file.
With C#, it seems that there is no such header file, as one class should contain both definition/implementation.
I wonder if the number of lines can be very big, because one can't separate the class into multiple files. Am I correct? I mean, in some cases, one can't change the class design to have smaller classes. In this case, is there a way to solve this problem?
You can separate a class into multiple files using the partial keyword
public partial class ClassNameHere
{
}
It is possible to split the definition of a class or a struct, or an interface over two or more source files using the Partial keyword modifier Link to msdn with the partial class
Partial classes only give you so much. There is still no way, that i know of, to split your class definition from implementation, such that each exists in a separate file. So if you like to develop based on a need-to-know paradigm then you are sort of stuck. Basically there are three levels a developer can work at...
1) Owns all the code and has access to, and maintains all of it.
2) Wishes to use some useful base class(s) which may form part of a framework, or may just be a useful class with some virtual methods, etc, and wishes to extend, or re-implement some virtual base class methods of interest. Now the developer should not need to go and look at the code in the base class(s) in order to understand things at a functional level. If you understand the job of a function, it's input and output parameters, there is no need to go and scratch inside source code. If you think there's a bug, or an optimization is needed, then refer to the developer from 1) who owns and maintains the base code. Of course there's nothing saying that 1) and 2) cannot be associated with the same developer, in which case we have no problem. In fact, this is more than often the case i suspect. Nevertheless, it is still good practice to keep things well separated according to the level at which you are working.
3) A developer needs to use an already packaged / sealed object / component dll, which exposes the relevant interfaces.
Within the context of c#, 1) and 3) have no problems. With 2) i believe there is no way to get round this (unless you change from exposing virtual base methods to exposing interface methods which can be reimplemented in a component owning the would-be base class). If i want to have a look at a class definition to browse over the methods, scaffolding functions, etc, i have to look at a whole lot of source code as well, which just gets in the way of what i am trying to focus on.
Of course if there is class definition documentation external to how we normally do it ( in headers and source files), then i must admit, that within the context of 2), there is not reason to ever look into a class definition file to gain functional knowledge.
So maybe clever Tom's came up with c#, decided to mix class definition with implementation in an attempt to encourage developers to have external documents for their class definitions, and interfaces, which in most IT companies is severely lacking.
Use a partial class as #sparks suggests, or, split into several classes. It's a good rule of thumb that, if you can't fit a class onto a couple of pages, it's complicated enough to need breaking apart.
I was wondering if its possible to change the default "program" class that gets created for any console application to a partial class.
I want to do this because I want better organisation rather than have all methods in 1 file categorized by region. It would make more sense for me to have certain method categories sitting in separate files.
My understanding of a partial class is that it is a class definition in multiple files that during a compile merges the class files into 1 class unit.
I could be wrong, or there could be a better way for me to achieve better organisational structure. Any suggestions would help, and thanks
You certainly can do that - but it sounds to me like you'd be better off splitting your code into multiple classes. If you've got multiple method "categories" those categories may well be natural class boundaries.
Generally speaking, the entry point class should be fairly small. That's not always the case, but it's a good rule of thumb. Usually its only purpose is to get the rest of the program running.
"Guidance Automation Toolkit" and "Guidance Automation Extension" provide option to extend the File -> New -> Project options and you can generate the code the way you like. You can use this only if you want to create initial code automatically while creating projects.
One example for Guidance Package is SmartClient Library (CAB+EL). Smartclient source code is available.
It is good to have separate files for single class. One example based on CAB/Composite Appliacation Block or Windows form application.
there would be view.cs and view.designer.cs and both are defining the same file. view.designer.cs is used specifically for GUI designer where developer normally won't edit. Developer edit view.cs.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I'm wondering why the 'partial class' concept even exists in C#/VB.NET. I'm working on an application and we are reading a (actually very good) book relavant to the development platform we are implementing at work. In the book, the author provides a large code base/wrapper around the platform API and explains how he developed it as he teaches different topics about the platform development.
Anyway, long story short - he uses partial classes, all over the place, as a way to fake multiple inheritance in C# (IMO). Why he didn't just split the classes up into multiple ones and use composition is beyond me. He will have 3 'partial class' files to make up his base class, each w/ 3-500 lines of code... And does this several times in his API.
Do you find this justifiable? If it were me, I'd have followed the S.R.P. and created multiple classes to handle different required behaviors, then created a base class that has instances of these classes as members (e.g. composition). Why did MS even put partial class into the framework? They removed the ability to expand/collapse all code at each scope level in C# (this was allowed in C++) because it was obviously just allowing bad habits - partial class is, IMO, the same thing. I guess my question is: Can you explain to me when there would be a legitimate reason ever to use a partial class?
EDIT: I'm aware that for Web/WinForms there is no other choice. But outside of this? Why didn't MS just put some different keyword for gluing code-genn'ed classes together? Or is there really a legit design scenario that merits it?
I do not mean this to be a rant / war thread. I'm honestly looking to learn something here. When should partial classes be used in code design? Simple question, no need to close
Thanks
Can you explain to me when there would be a legitimate reason to ever use a partial class?
One of the most legitimate and useful reasons is to encourage the separation of automatically generated code and your own custom extensions to it. For instance, it's common to have an automatically generated form code from some kind of designer, but you usually want to add your own specific behavior to it. This way, if you regenerate the automatic-code portion, you're not touching the part that has your specific extensions.
That said, it's quite possible to have too much of a good thing. Some tips:
Don't make your classes partial for the sake of being partial.
Don't put partial classes anywhere except besides one another. If you have to jump to a completely unrelated section of the project to see the other half of the class, you're probably doing it wrong.
Don't use partial as a technique to obscure the size of the class. If you're breaking up your classes with partial because they're too big, you should revisit the Single Responsibility Principle.
If you have three or more partial fragments for the same class, it's almost a guarantee that you're abusing partial. Two is the typical upper bound of reasonableness, and it's generally used to segment automatically-generated code from handwritten code.
Anyway, long story short - he uses partial classes, all over the place, as a way to fake multiple inheritance in C# (IMO). Why he didnt just split the classes up into multiple ones and use composition is beyond me. He will have 3 'partial class' files to make up his base class, each w/ 3-500 lines of code... And does this several times in his API.
Yes, that's definitely a clear abuse of partial!
There are two reasons that I would (and do) use partial classes.
To separate auto-generated portions of the code (such as WinForms designer code or T4 output).
To allow nested types their own file while still achieving the encapsulation required by your design.
Update
I can see that some are not convinced about my second point, so let me give an example; the ListViewItemCollection in the framework. It is quite rightly nested under ListView because it is only for use by ListView, but to make maintenance much easier, I would give it it's own file by using partial classes. I don't see this as bad design or a misuse of the partial keyword.
For more discussion, check out the question that this one duplicates: Partial Classes in C#
Another legitimate use of partial classes is to help reduce the "monolithic web service" clutter in WCF. You want to to break it down into logical groups of functionality but don't want to have to create a ream of individual service instances/endpoints (presumably because they share state, resources, and so on).
The solution? Have the service implement multiple interfaces, and implement each interface in its own partial class. Then map different endpoints in the configuration to the same physical implementation. It makes the project a lot more maintainable, but you still only have one physical endpoint.
In some cases I'd point to this type of approach as a poor practice on account of the SRP, but when you're working with WCF services or web services in general, it's not quite so simple. You have to balance internal design requirements against external consumption requirements.
One less common use might be to split up a huge class into separate physical files to make life easier from a source control point of view. I've just joined a project containing some enormously bloated web service classes running to thousands of lines of code and with methods related to several different business functions.
Merging from various feature branches is a nightmare due to different teams making simultaneous unrelated changes in the same file. I can't split the web service up without making some seriously breaking changes, but breaking the class up into partial classes preserves the behaviour exactly, and removes a whole bunch of merging issues.
I'm definitely not encouraging the above as a design choice, but it was a nice quick win for us, and goes to show that partials aren't evil all the time...
I've used partial classes in many different ways in the past. As I learn more about programming and in particular the concept of "favor composition over inheritance" I can easily see the need diminishing for both vertical inheritance and overuse of partial classes.
Other than auto-generated code, I cannot think of good use of partial classes. Even if you use EF, and need different metadata, they don't even recommend using partials for metadata. In fact if you try to duplicate any properties in another partial(just to add metadata) you'll get a compiler error.
The more we learn about refactoring and SOC (Separation of Concerns) the smaller and more focused our classes become. They are by default, re-used, which over time makes them bullet-proof and easily tested. Just say NO to gargantuan programs. Henry Ford learned this concept in the early 1900's programmers started learning it 100 years later.
Use composition when you can...
I fully agree with John's answer. But I would take it one step further.
Don't make your classes partial.
The only use of partial classes I can think of that I would consider "good design" is with automatically generated code. Any other use is almost certainly unnecessarily splitting up your class. (Actually, I can see that Jeff's second point on nested classes is possibly a valid use)
Personally I think this book you are reading sounds like bad design, however do consider that he may just be using partial classes so he can just demo part of the code little bits at a time rather than just presenting the whole class in one go.
Can you explain to me when there would be a legitimate reason to ever use a partial class?
Recent versions of Visual Studio use partial classes to seperate the auto-generated designer code from your own code..
An ASP.NET example:
Page.aspx
Page.aspx.cs <- Your code
Page.aspx.Designer.cs <- A partial class containing auto generated code.
A WinForms example:
Form1.resx
Form1.cs <- Your code
Form1.Designer.cs <- A partial class containing auto generated code
I've used partial classes to "physically" separate static data access methods from business class properties and methods in an active record architecture. For example, we had Company and CompanyData partial classes side-by-side. The advantage was that one file was the POCO and the other contained only data access methods. This was a stepping stone to removing data access to repository classes in a legacy application. I think that was a legitimate use, it certainly made the re-factoring process saner.
Another good use for partial classes would be when implementing the Abstract factory pattern. Make the root factory object partial and then place the actual factory methods in the same file as the class the factory instantiates.
EDIT: Partial classes also work well for classes that interact with a configuration file. Place the code containing the configuration parameters near the code that actually uses the configuration parameter.
Just stumbled across this thread while googling the benefits of partial class.
I am in the process of converting a Java EE application into a silverlight based .NET one.
I came across the following code in the view layer :
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.225
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
...
public partial class Wwcusts04d : System.Windows.Controls.Page {
Now, if the partial page itself is autogenerated, what's the use of maintaining it ?
Also, the code inside just links various controls to their names. I don't confess to have knowledge of silverlight, but isnt this thing better suited in xaml?
Partial class exists in the .Net framework solely to let Visual Studio designers (e.g. the Asp.Net designer and the Windows Forms designer) to generate code / mess with your classes while keeping that generated code in a separate file.
(See .NET Partial Classes vs. Inheritance)
If you do something similar (generate code that needs to coexist with user-written code) then you might also find partial classes useful, but I don't believe that Microsoft ever intended partial classes as a language concept to be useful to anyone other than the Visual Studio team.
Its not so much that using Partial classes is bad design - its just you probably wont find a use for them.
I've used a partial class twice in VB.Net, and both times were for the rare occasion that I needed late binding. Simply create a partial class and turn Option Strict Off at the top.
Just to add on to the previous answers that mentioned separating generated code from custom code, I've found partial classes useful for extending strongly-typed datasets.
There's a lot of discussion out there on this topic, and lots of people saying that 1) it's bad design to use partial classes, 2) that it's used for autogenerated code, and 3) that it shouldn't take the place of inheritance.
I have a situation, though, in which partial classes look like they'll come in very handy: I'm building a series of applications which will eventually be integrated into a suite. They'll all have a main form which will provide some functionality, and several shared components (e.g., a form to display reports). While I could define a base class and inherit from it, that would mean a lot of rework when the time comes to combine all of the applications into the "enterprise" version of the product.
Thus, partial classes are quite useful, because I can quite simply include the various partial classes into the combined version, while still allowing me to build the individual, stand-alone versions of the product. If I were to try to accomplish this using inheritance, I'd end up with each component calling its own version of the common components (e.g., InvoiceReportViewer, PurchasingReportsViewer, etc.) rather than simply calling ReportsViewer and knowing that Visual Studio will have integrated all of the bits for me.
Another thing to consider, partial classes forces you to create different file names which contains same class name. For example you have FactoryClass and you are creating partial versions of it like; Factory.designer.cs, Factory.data.cs and all those files has class named FactoryClass.
If you navigate to this question; there is a best practice defined as:
Best practice, however, is to define one class per file and to give the file the same name as the class (or struct, etc.) being defined.
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.