C# Extend a Library Class to Rest of Program - c#

I have a public Library class with all the global variables needed for my program to work. It is structured like this:
public static class Library
{
public static string globalString = "";
}
In other languages, it is possible to use extends to extend a class to another class so the 'Library' prefix is not required on global variables but in C# it works a bit differently. I tried adding it after the colon in the class I wanted to extend to (like this: public partial class Login : Form, Library) and I was told that "Classes cannot have multiple base classes". Apparently, it is possible to use interfaces to extend classes but I do not fully understand how that works or how to implement it.

If you're using one of the newer versions of C#, you can import a static class so that you use its members without fully qualifying their names. In C#, the syntax would be...
using static RootNamespace.Library;
// Provided the class Library is in a namespace called RootNamespace
The above line would be placed at the top of your code file, in this case I'm assuming it's in Login.cs. This will be among the other using statements like using System; and you will be able to use the public static members of Library inside your Login class.
I would recommend using something other than global variables though, such as properties so that you can encapsulate some logic and protect against invalid states by running some validation before these values are changed.

Related

Using protobuf-net with code auto-generated (from WSDL spec in this case)

My problem is similar to this one, except that the code I want to use with protobuf-net was generated by the WSDL utility. "They tell me" that it's not appropriate to plan to modify the generated code (to add attributes).
It would be odd to write something to build a matching set of DTO classes, given that (other than the methods described) all the classes are already public (partial) classes marked with [Serializable] and have all public properties -- that is, they are very DTO-like already.
The simplest solution I've seen is to violate the rules and modify the code. If all strings in the generated C# file
public partial class
are replaced with
[ProtoBuf.ProtoContract(ImplicitFields = ProtoBuf.ImplicitFields.AllPublic)]
public partial class
from my limited testing that will do the trick. Does a better solution exist? Is there something wrong with using that technique (other than that I'm modifying generated code)?
Type-level attributes in partial classes can be added in separate code files. All you need is a separate file with just:
[ProtoBuf.ProtoContract(ImplicitFields = ProtoBuf.ImplicitFields.AllPublic)]
public partial class {}
it must also be in the right namespace, but you didn't say which, so probably:
namespace Foo {
[ProtoBuf.ProtoContract(ImplicitFields = ProtoBuf.ImplicitFields.AllPublic)]
public partial class {}
}

C#: Is it possible to have partial extension classes

I am looking to create Extension classes that extend Entity Framework Entities in a different assembly to the EF Entities. I also want to code gen some additional/generic methods in an extension methods class (using T4), then have the ability to create a partial extension methods class with additional custom methods. Is this possible.
You don't need them. Just write another extension class.
namespace Namespace1
{
public static class MyEntityBlibblingExtensions
{
public void Blibble(this MyEntity self)
{
// ...
}
}
}
Then, elsewhere...
namespace Namespace2
{
public static class MyEntityFurtlingExtensions
{
public void Furtle(this MyEntity self)
{
// ...
}
}
}
Anything importing Namespace1 will see the extension method Blibble() while anything importing Namespace2 will see Furtle(), and importing both will see both. They can be in different assemblies or anywhere which imports MyEntity's namespace. So, partial extensions aren't really a valid concept. In fact, the very idea of putting extension methods inside classes is a bit of a hack as it is - a shame they couldn't unbend C#'s rules enough to let extension methods live outside of classes.
Yes - i tried it and it worked.
There is no such thing as an "extension" class - there are only extension methods which must be inside a "static" class.
You can have static partial classes.
UPDATE: Sorry I read your heading but not the text of your question.
The answer is still yes, but why not just create new classes? I can't see how having a partial class really helps in this case.
The main problem I can see here is the phrase "in a different assembly". If it wasn't for that, you could just add your methods etc in an additional partial class with regular instance methods, and it would all be fine.
You can have static partial classes, however you cannot use partial classes to add to a type in another assembly. Extension methods work fine from a partial class, although note that partial classes are purely a mechanism for splitting code between different files. You could just as easily have multiple static classes for the extension methods.

Using the generated .net classes to extend own classes. HowTo?

I used the OWLGrinder to create the assembly and imported the library into my project. That works fine. Now I want to write my own set of classes. Therefore I extended these with the equivalent of the assembly. But it just doesn't work.
The ontology holds a class named ManagementObject.
I created another Class (C#) called RealWorldObject:
public class RealWorldObject : ManagementObject
{
public RealWorldObject(string uri) : base(uri) { }
public RealWorldObject(string uri, RdfDocument rdfdocument) : base(uri, rdfdocument) { }
public RealWorldObject(RdfDocument rdfdocument) : base(rdfdocument) { }
public String getClassName()
{
return this.OwlClassName;
}
public static RdfDocument addRealWorldObjectIndividualt(RdfDocument rdfDocument)
{
Vehicle vehicle = new Vehicle("vehicle1", rdfDocument);
FixedEvent fxE1 = new FixedEvent("autoGekauft", rdfDocument);
fxE1.agent = new xmlns.com.foaf._01.Person("robert", rdfDocument);
vehicle.hasFixedEvent = fxE1;
return rdfDocument;
}
Which leads to the error:
ObjectManagement.Object.RealWorldObject does declare one (and only one) OwlClassAttribute. This is an implementation bug of the plugin.
How else should I extend the generated classes by the OWLGrinder.
Thx it is a long time ago that I used C#, so I'm kind of rusty.
The auto-generated classes produced by OwlGrinder.exe have not been designed for inheritance in mind. I am not saying it is wrong, it is just not designed for that. The auto-generated classes contain plenty of metadata defined as class attributes and inheritance hides all of that. The infrastructure counts on the presence of these attributes and if they are hidden, you get these runtime error messages.
Using Visual Studio Object Browser, take a look of the attributes over the auto-generated classes. OwlClassAttribute, SubClassOfAttribute, LightVersionAttribute are certainly mandatory. You may simply copy/paste the class attributes of ManagementObject on the top of your RealWorldObject class. I assume, it will work. But again, you might bump into additional show stoppers, as you do not follow the default routes ROWLEX has been designed for. This is a bit living on the edge :)
Instead of inheritance, you might consider reverse engineering your auto-generated assembly to C# using Reflector or other tools. Having the source code in your hand, you may modify the generated classes directly. You might make your ManagementObject class partial, and implement your additional methods in a separate file.

Can you create private classes in C#?

This is a question for the .NET philosophers:
It is my understanding that Microsoft consciously denied use of private classes in C#. Why did they do this and what are their arguments for doing so?
I, for example, am building a large application that includes a reporting tool. This tool uses a lot of business objects that are used only within the reporting tool and not in other parts of the project. I want to encapsulate them for use only within the reporting tool itself.
Great decision is creating separate project in VS for this tool, and I'll do like that, but I'm interesting, what if I can't do this - for exmple our architecture wasn`t good enough, and we have big single project.
Behind "private class" I mean a class that can't be used in any other namespace, except its own.
My question was not - how can I simulate this, or do in another way. I'm just wondering, why not use private keyword with class keyword without any parent classes. I`m thinking there should be some reason, and I want to know it
Allowing classes to be private to a namespace would achieve no meaningful level of protection.
Any assembly in the world could simply reference your dll, and start writing code in your namespace which accesses your supposedly private classes.
I think that's possibly the answer you'd get from Microsoft.
There's a workaround for this, but you might not like it.
Instead of using a namespace to scope your classes, use a public static partial class:
Before:
namespace MyCompany.Foo {
class Bar { }
public class Baz { }
}
After:
namespace MyCompany {
public static partial class Foo {
private class Bar { }
public class Baz { }
}
}
This construct, like a namespace, can span multiple files in the same project. But unlike a namespace, it cannot "escape" from your project (other projects cannot define other members inside Foo).
There's an added advantage that you can have utility methods that seem to have no class for code inside Foo.
The disadvantage is that, to use your non-private classes outside of your fake namespace, you have to reference them inside Foo:
using MyCompany;
// ...
var baz = new Foo.Baz();
This can be mitigated by using an alias for the class:
using Baz = MyCompany.Foo.Baz;
// ...
var baz = new Baz();
But you'd have to do it for each non-private class that you want to use.
UPDATE
It's interesting to note that C# 6 will have static using statements, which could effectively improve this proposal to use a public static partial class as a "module". You would just "use" the "module" to access its types directly.
Hopefully, it will work like this:
using MyCompany.Foo;
// ...
var baz = new Baz();
Just as if Foo was a namespace.
You can create a private class, as a member of another type:
public class Outer {
// ...
private class Inner {
// ...
}
}
and Inner is only visible to members of Outer.
At the outermost level (i.e. in a namespace) private as per its definition would not make sense (since there is nothing to be private in). Instead use internal (visible to the containing assembly's members only).
You can define a private class, but it can only be used by its containing class.
If you want a class that is only visible within a particular assembly (DLL/EXE/etc.), then you should declare it as internal (Friend in VB)
True but you can get a pretty close simulation of this with internal classes and the internalsvisibletoAttribute if the namespace is split across multiple assemblies.
Also remember that a class within another can be private to the outer class. The outer class can be considered a namespace for this purpose.
So I guess you want to do this
namespace Baz
{
private class foo
{
private int _bar;
}
}
If yes. Then what is the purpose foo will server. At namespace can you be more restrictive than internal , and make any use of the class.If I could do this where will I use this .
That is why you have this compile time validation.
Now Inside a Public Class it makes sense to have a private class. I cannot explain it better this Private inner classes in C# - why aren't they used more often?.

When is it appropriate to use C# partial classes?

I was wondering if someone could give me an overview of why I would use them and what advantage I would gain in the process.
The biggest use of partial classes is to make life easier for code generators / designers. Partial classes allow the generator to simply emit the code they need to emit and they do not have to deal with user edits to the file. Users are likewise free to annotate the class with new members by having a second partial class. This provides a very clean framework for separation of concerns.
A better way to look at it is to see how designers functioned before partial classes. The WinForms designer would spit out all of the code inside of a region with strongly worded comments about not modifying the code. It had to insert all sorts of heuristics to find the generated code for later processing. Now it can simply open the designer.cs file and have a high degree of confidence that it contains only code relevant to the designer.
Another use is to split the implementation of different interfaces, e.g:
partial class MyClass : IF3
{
// main implementation of MyClass
}
partial class MyClass : IF1
{
// implementation of IF1
}
partial class MyClass : IF2
{
// implementation of IF2
}
Aside from the other answers...
I've found them helpful as a stepping-stone in refactoring god-classes. If a class has multiple responsibilities (especially if it's a very large code-file) then I find it beneficial to add 1x partial class per-responsibility as a first-pass for organizing and then refactoring the code.
This helps greatly because it can help with making the code much more readable without actually effecting the executing behavior. It also can help identify when a responsibility is easy to refactor out or is tightly tangled with other aspects.
However--to be clear--this is still bad code, at the end of development you still want one responsibility per-class (NOT per partial class). It's just a stepping-stone :)
Multiple Developer Using Partial Classes multiple developer can work on the same class
easily.
Code Generator Partial classes are mainly used by code generator to keep
different concerns separate
Partial Methods Using Partial Classes you can also define Partial methods as well where a developer can simply define the method and the other developer can implement that.
Partial Method Declaration only Even the code get compiled with method declaration only and if the implementation
of the method isn't present compiler can safely remove that piece of
code and no compile time error will occur.
To verify point 4. Just create a winform project and include this line after the Form1 Constructor and try to compile the code
partial void Ontest(string s);
Here are some points to consider while implementing partial classes:-
Use partial keyword in each part of partial class.
The name of each part of partial class should be the same but the source file name for each part of partial class can be different.
All parts of a partial class should be in the same namespace.
Each part of a partial class should be in the same assembly or DLL, in other words you can't create a partial class in source files from a different class library project.
Each part of a partial class must have the same accessibility. (i.e: private, public or protected)
If you inherit a class or interface on a partial class then it is inherited by all parts of that partial class.
If a part of a partial class is sealed then the entire class will be sealed.
If a part of partial class is abstract then the entire class will be considered an abstract class.
One great use is separating generated code from hand-written code that belong in the same class.
For example since LINQ to SQL uses partial classes you can write your own implementation of certain pieces of functionality (like Many-to-Many relationships) and those pieces of custom code won't get overwritten when you re-generate the code.
The same goes for WinForms code. All the Designer generated code goes in one file that you generally don't touch. Your hand-written code goes in another file. That way, when you change something in Designer, your changes don't get blown away.
It is true that Partial Class is used in auto code generation, one use can be maintaining a large class file which might have thousand lines of code. You never know your class might end up with 10 thousand lines and you don't want to create a new class with different name.
public partial class Product
{
// 50 business logic embedded in methods and properties..
}
public partial class Product
{
// another 50 business logic embedded in methods and properties..
}
//finally compile with product.class file.
Another possible use could be that more than one developer can work on the same class as they are stored at different places. People might laugh but you never know it can be handful sometimes.
Product1.cs
public partial class Product
{
//you are writing the business logic for fast moving product
}
Product2.cs
public partial class Product
{
// Another developer writing some business logic...
}
Hope it makes sense!
Partial classes span multiple files.
How can you use the partial modifier on a C# class declaration?
With partial classes, you can physically separate a class into multiple files. This is often done by code generators.
Example
With normal C# classes, you cannot declare a class in two separate files in the same project. But with the partial modifier, you can.
This is useful if one file is commonly edited and the other is machine-generated or rarely edited.
Here's an example to clarify:
class Program
{
static void Main()
{
A.A1();
A.A2();
}
}
Contents of file A1.cs: C#
using System;
partial class A
{
public static void A1()
{
Console.WriteLine("A1");
}
}
Contents of file A2.cs: C#
using System;
partial class A
{
public static void A2()
{
Console.WriteLine("A2");
}
}
Output:
A1
A2
Partial is required here.
If you remove the partial modifier, you will get an error containing this text:
[The namespace '<global namespace>' already contains a definition for 'A'].
Tip:
To fix this, you can either use the partial keyword, or change one of the class names.
How does the C# compiler deal with partial classes?
If you disassemble the above program (using IL Disassembler), you will see that the files A1.cs and A2.cs are eliminated. You will find that the class A is present.
Class A will contain the methods A1 and A2 in the same code block. The two classes were merged into one.
Compiled result of A1.cs and A2.cs: C#
internal class A
{
// Methods
public static void A1()
{
Console.WriteLine("A1");
}
public static void A2()
{
Console.WriteLine("A2");
}
}
Summary
Partial classes can simplify certain C# programming situations.
They are often used in Visual Studio when creating Windows Forms/WPF programs.
The machine-generated C# code is separate.
Or You could find the whole description here.
keep everything as clean as possible when working with huge classes, or when working on a team, you can edit without overriding (or always commiting changes)
The main use for partial classes is with generated code. If you look at the WPF (Windows Presentation Foundation) network, you define your UI with markup (XML). That markup is compiled into partial classes. You fill in code with partial classes of your own.
As an alternative to pre-compiler directives.
If you use pre-compiler directives (namely #IF DEBUG) then you end up with some gnarly looking code intermingled with your actual Release code.
You can create a seperate partial-class to contain this code, and either wrap the entire partial class in a directive, or omit that code-file from being sent to the compiler (effectively doing the same).
If you have a sufficiently large class that doesn't lend itself to effective refactoring, separating it into multiple files helps keep things organized.
For instance, if you have a database for a site containing a discussion forum and a products system, and you don't want to create two different providers classes (NOT the same thing as a proxy class, just to be clear), you can create a single partial class in different files, like
MyProvider.cs - core logic
MyProvider.Forum.cs - methods pertaining specifically to the forum
MyProvider.Product.cs - methods for products
It's just another way to keep things organized.
Also, as others have said, it's about the only way to add methods to a generated class without running the risk of having your additions destroyed the next time the class is regenerated. This comes in handy with template-generated (T4) code, ORMs, etc.
Most people remark that partial should only be used for a class that has a generated code file or for interfaces. I disagree, and here is why.
For one example, let's look at the C# System.Math class... that's class. I would not attempt to stuff 70+ methods all into the same single code file. It would be a nightmare to maintain.
Placing each math method into individual partial class files, and all code files into a Math folder in the project, would be significantly cleaner organization.
The same could/would hold true for many other classes that have a large amount of diverse functionality. For example a class for managing the PrivateProfile API might benefit by being split into a clean set of partial class files in a single project folder.
Personally, I also split what most people call "helper" or "utility" classes into individual partial files for each method or method functional group. For example on one project the string helper class has almost 50 methods. That would be a long unwieldy code file even using regions. It is significantly easier to maintain using individual partial class files for each method.
I would just be careful using partial classes and keep all code file layout consistent throughout the project when doing this. Such as placing any class public enums and class private members into a Common.cs or similarly named file in the folder, instead of spreading them out across the files unless they are specific to only the partial file they are contained in.
Keep in mind that when you split a class into separate files you also lose the ability to use the text editor splitter bar that lets you view two different sections of a current file simultaneously.
Another use i saw is,
Extending a big abstract class regarding data access logic ,
i have various files with names Post.cs,Comment.cs,Pages.cs...
in Post.cs
public partial class XMLDAO :BigAbstractClass
{
// CRUD methods of post..
}
in Comment.cs
public partial class XMLDAO :BigAbstractClass
{
// CRUD methods of comment..
}
in Pages.cs
public partial class XMLDAO :BigAbstractClass
{
// CRUD methods of Pages..
}
Service references are another example where partial classes are useful to separate generated code from user-created code.
You can "extend" the service classes without having them overwritten when you update the service reference.
Partial classes make it possible to add functionality to a suitably-designed program merely by adding source files. For example, a file-import program could be designed so that one could add different types of known files by adding modules that handle them. For example, the main file type converter could include a small class:
Partial Public Class zzFileConverterRegistrar
Event Register(ByVal mainConverter as zzFileConverter)
Sub registerAll(ByVal mainConverter as zzFileConverter)
RaiseEvent Register(mainConverter)
End Sub
End Class
Each module that wishes to register one or more types of file converter could include something like:
Partial Public Class zzFileConverterRegistrar
Private Sub RegisterGif(ByVal mainConverter as zzFileConverter) Handles Me.Register
mainConverter.RegisterConverter("GIF", GifConverter.NewFactory))
End Sub
End Class
Note that the main file converter class isn't "exposed"--it just exposes a little stub class that add-in modules can hook to. There is a slight risk of naming conflicts, but if each add-in module's "register" routine is named according to the type of file it deals with, they probably shouldn't pose a problem. One could stick a GUID in the name of the registration subroutine if one were worried about such things.
Edit/Addendum
To be clear, the purpose of this is to provide a means by which a variety of separate classes can let a main program or class know about them. The only thing the main file converter will do with zzFileConverterRegistrar is create one instance of it and call the registerAll method which will fire the Register event. Any module that wants to hook that event can execute arbitrary code in response to it (that's the whole idea) but there isn't anything a module could do by improperly extending the zzFileConverterRegistrar class other than define a method whose name matches that of something else. It would certainly be possible for one improperly-written extension to break another improperly-written extension, but the solution for that is for anyone who doesn't want his extension broken to simply write it properly.
One could, without using partial classes, have a bit of code somewhere within the main file converter class, which looked like:
RegisterConverter("GIF", GifConvertor.NewFactory)
RegisterConverter("BMP", BmpConvertor.NewFactory)
RegisterConverter("JPEG", JpegConvertor.NewFactory)
but adding another converter module would require going into that part of the converter code and adding the new converter to the list. Using partial methods, that is no longer necessary--all converters will get included automatically.
Partial classes recently helped with source control where multiple developers were adding to one file where new methods were added into the same part of the file (automated by Resharper).
These pushes to git caused merge conflicts. I found no way to tell the merge tool to take the new methods as a complete code block.
Partial classes in this respect allows for developers to stick to a version of their file, and we can merge them back in later by hand.
example -
MainClass.cs - holds fields, constructor, etc
MainClass1.cs - a developers new code as they implement
MainClass2.cs - is another developers class for their new code.
From MSDN:
1.At compile time, attributes of partial-type definitions are merged. For example, consider the following declarations:
[SerializableAttribute]
partial class Moon { }
[ObsoleteAttribute]
partial class Moon { }
They are equivalent to the following declarations:
[SerializableAttribute]
[ObsoleteAttribute]
class Moon { }
The following are merged from all the partial-type definitions:
XML comments
interfaces
generic-type parameter attributes
class attributes
members
2.Another thing, nested partial classes can be also partial:
partial class ClassWithNestedClass
{
partial class NestedClass { }
}
partial class ClassWithNestedClass
{
partial class NestedClass { }
}
Here is a list of some of the advantages of partial classes.
You can separate UI design code and business logic code so that it is easy to read and understand. For example you are developing an web application using Visual Studio and add a new web form then there are two source files, "aspx.cs" and "aspx.designer.cs" . These two files have the same class with the partial keyword. The ".aspx.cs" class has the business logic code while "aspx.designer.cs" has user interface control definition.
When working with automatically generated source, the code can be added to the class without having to recreate the source file. For example you are working with LINQ to SQL and create a DBML file. Now when you drag and drop a table it creates a partial class in designer.cs and all table columns have properties in the class. You need more columns in this table to bind on the UI grid but you don't want to add a new column to the database table so you can create a separate source file for this class that has a new property for that column and it will be a partial class. So that does affect the mapping between database table and DBML entity but you can easily get an extra field. It means you can write the code on your own without messing with the system generated code.
More than one developer can simultaneously write the code for the class.
You can maintain your application better by compacting large classes. Suppose you have a class that has multiple interfaces so you can create multiple source files depending on interface implements. It is easy to understand and maintain an interface implemented on which the source file has a partial class.
I find it disturbing that the word 'cohesion' does not appear anywhere in these posts (until now).
And I'm also disturbed that anyone thinks enabling or encouraging huge classes and methods is somehow a good thing.
If you're trying to understand and maintain a code-base 'partial' sucks.
Whenever I have a class that contains a nested class that is of any significant size/complexity, I mark the class as partial and put the nested class in a separate file. I name the file containing the nested class using the rule: [class name].[nested class name].cs.
The following MSDN blog explains using partial classes with nested classes for maintainability: http://blogs.msdn.com/b/marcelolr/archive/2009/04/13/using-partial-classes-with-nested-classes-for-maintainability.aspx
I know this question is really old but I would just like to add my take on partial classes.
One reason that I personally use partial classes is when I'm creating bindings for a program, especially state machines.
For example, OpenGL is a state machine, there are heaps of methods that can all be changed globally, however, in my experience binding something similar to OpenGL where there are so many methods, the class can easily exceed 10k LOC.
Partial classes will break this down for me and help me with finding methods quickly.
Partial classes are primarily introduced to help Code generators, so we (users) don't end up loosing all our work / changes to the generated classes like ASP.NET's .designer.cs class each time we regenerate, almost all new tools that generate code LINQ, EntityFrameworks, ASP.NET use partial classes for generated code, so we can safely add or alter logic of these generated codes taking advantage of Partial classes and methods, but be very carefully before you add stuff to the generated code using Partial classes its easier if we break the build but worst if we introduce runtime errors. For more details check this https://web.archive.org/web/20211020111732/https://www.4guysfromrolla.com/articles/071509-1.aspx
I note two usages which I couldn't find explicitly in the answers.
Grouping Class Items
Some developers use comments to separate different "parts" of their class. For example, a team might use the following convention:
public class MyClass{
//Member variables
//Constructors
//Properties
//Methods
}
With partial classes, we can go a step further, and split the sections into separate files. As a convention, a team might suffix each file with the section corresponding to it. So in the above we would have something like: MyClassMembers.cs, MyClassConstructors.cs, MyClassProperties.cs, MyClassMethods.cs.
As other answers alluded to, whether or not it's worth splitting the class up probably depends on how big the class is in this case. If it's small, it's probably easier to have everything in one master class. But if any of those sections get too big, its content can be moved to a separate partial class, in order to keep the master class neat. A convention in that case might be to leave a comment in saying something like "See partial class" after the section heading e.g.:
//Methods - See partial class
Managing Scope of Using statements / Namespace
This is probably a rare occurrence, but there might be a namespace collision between two functions from libraries that you want to use. In a single class, you could at most use a using clause for one of these. For the other you'd need a fully qualified name or an alias. With partial classes, since each namespace & using statements list is different, one could separate the two sets of functions into two separate files.

Categories