Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Practical usage of partial keyword in C#

Tags:

c#

.net

class

I know it lets visual studio to separate WinForms UI code from the UI events, etc. But are there any practical uses for it?

like image 278
Joan Venge Avatar asked Mar 04 '09 22:03

Joan Venge


People also ask

What is the use of partial keyword?

The partial keyword indicates that other parts of the class, struct, or interface can be defined in the namespace. All the parts must use the partial keyword. All the parts must be available at compile time to form the final type. All the parts must have the same accessibility, such as public , private , and so on.

In what scenarios do we use partial classes?

The biggest use of partial classes is in technologies where there is code generation. The Microsoft team themselves use partial classes in ASP.NET, LINQ, and EF code generation. For instance, when we look at ASP.NET there are two parts, one is the auto-generated code of a page and the other is the code you write.

What is the use of partial classes in C hash?

A partial class is a special feature of C#. It provides a special ability to implement the functionality of a single class into multiple files and all these files are combined into a single class file when the application is compiled.

What is partial class and what all are the advantages of partial class?

Partial Class in C# A partial class splits the definition of a class over two or more source (. cs) files. You can create a class definition in multiple physical files but it will be compiled as one class when the classes are compiled.


2 Answers

The partial keyword is typically used in code generation utilities to allow developers to add additional functionality to the generated code without the fear of that code being erased if the code is generated again.

With C# 3 the partial keyword can be applied to methods to allow users of generated code to fill in blanks left by the generator. The Linq To Sql designer for example provides partial methods that allow you to add logic to the classes that the framework will call if implemented. The benefit here is that the C# compiler will completely remove unimplemented partial methods, so there is no performance hit at all for not implementing them.

Partial classes can also be used to organize very large classes into separate code files, although this sort of usage is usually a sign that your classes are too large and are taking on too many responsibilities.

like image 54
Erik Forbes Avatar answered Nov 10 '22 17:11

Erik Forbes


The best use for the partial keyword that I can think of is nested classes. Without the partial keyword all nested classes must go in the same code file as the containing class.

like image 29
snarf Avatar answered Nov 10 '22 17:11

snarf