Partial Class Winform Form - c#

It was taught to me that any alterations to an object on a form (change the text, make visible/invisible or change the color and so on) should be done in the corresponding form class.
But due to the large amount of such alterations done inside the project, the file has became large and hard to search through. I've read online that a Partial Class could help, but there was no explanation on how to implement this. As an easy example, I have the following 2 files:
Form_Main.cs
namespace Test
{
partial class Form_Main : Form
{
public Form_Main()
{
InitializeComponent();
}
}
}
AND Form_Main.Dataloader.cs
namespace Test
{
partial class Form_Main : DataLoader
{
public void SetText()
{
TextBox_StudentSurname.Text = "1";
}
}
}
How can I make this work? Because if I do this I get several errors in the designer.

Your main problem is the first error printed: You cannot declare different base classes in different partial implementations. I don't know which of the two base classes is the right one (the one you previously used), but as always, a class cannot have two base classes. It is legal to specify the base class only in one of the parts, but if it is specified multiple times, it must be the same.

Related

C# - private static method in partial class not shared between files?

I'm creating static partial class like this.
If I put them in the same file there is no problem, but when I move one class to another file in the same project, this method private_method_from_a() does not exist anymore.
Is this by design? Do I miss something here?
//File A
public static partial class PartialClass
{
private static void private_method_from_a()
{
//Do something
}
}
//File B
public static partial class PartialClass
{
public static void public_method_b()
{
private_method_from_a();
}
}
Most likely the two files are in different namespaces, as #MickyD suggested in a comment. The reason for this problem is you're then making 2 different classes entirely. Chances are, one of them is in the namespace of your project, while the other is in the global namespace - that is, you didn't specify a namespace for it at all. Here's how the compiler sees them (suppose your project is called "MyProject", and has that name as the top-level namespace):
partial class global::MyProject.PartialClass
and
partial class global::PartialClass
Well, that's two distinct types, with different fully qualified names, both partial.
Make sure they're are both in the same namespace for the C# compiler to treat them as the same type.

access methods from plain code files and call it in main class (like php include)

This was a general question asked by a colleague of mine....
Is it possible to "outsource" code, and then call it in the main class (e.g. Form1.cs)?
This originates from the fact that he wants to organize his amount of code better than with regions, in the main class.
My first thought was - of course it is!
Use static Extentions, reference it to the main class, and call it through this.Method().
But he meant something like the "include" pattern in PHP....
Is that even possible?
he wants to organize his amount of code better than with regions, in the main class.
You can use partial classes to split the implementation of a single class into multiple (and perhaps more manageable) source files.
In File1.cs:
public partial class MyClass {
public void F() { ... }
}
In File2.cs:
public partial class MyClass {
public void G() { ... }
}
MyClass now has two methods, F and G.
You can externalize using partial classes or decouple it using c# assembly (dll).

Can partial class access static methods in C#?

The tutorial application, MusicStore -MVC3 (92 PageNo), created a POCO class like:
public partial class ShoppingCart
{
MusicStoreEntities storeDB = new MusicStoreEntities();
public static ShoppingCart GetCart(HttpContextBase context)
{
var cart = new ShoppingCart();
cart.ShoppingCartId = cart.GetCartId(context);
return cart;
}
}
How can we access static method in partial classes? In my opinion, we cannot access static methods in a partial class. The partial attribute means other parts of the class will be included in the namespace. In this scenario, I do not know where this other partial class is implemented.
My questions about this static method are:
Can we access static methods in partial classes? If so, how?
Where is this partial class implemented in this MusicStore application? I am not able to find the other part of this class's implementation.
Updated: There is no other ShoppingCart class in the models directory. Does anyone know where that partial implementation would be?
A partial class in C# can definitely access static methods. The partial attribute simply says a class can (not must) be defined accross multiple files and otherwise doesn't affect member lookup.
EDIT Responding to comment in question
A possible explanation for why you can't find the other implementation of ShoppingCart is it may not exist. A partial class is not required to have multiple definitions. The partial only means there may be other parts of the definition.
Yes, you can access static methods in partial classes.
Partial classes are just a way of representing a regular class in multiple source files, often with some of those source files controlled (or generated) by tools.
You can call ShoppingCart.GetCart(context) anywhere - it's a normal public static method.
It's still not really clear what your second question means, but there doesn't have to be another part at all. It's fine (though unusual) to have a partial class which is only declared in a single file.

Organizing c# code into different files

I've gotten to a point where my main code file is about a thousand lines long and it's getting un-manageable; that is, I'm starting to get confused and not know where to locate some things. It's well-commented but there's just too much stuff.
I'd really like to be able to organize my code into different files, each with its own purpose. I want to get all the help VS gives me as I type when I edit these other files. A picture can say a thousand words:
alt text http://img64.imageshack.us/img64/7848/codeorganizationscreens.png
Is what I'm trying to do even possible?
Yes, but you need to be in the same namespace and declare the class just like you did in the main file, an example:
file1.cs
namespace Names
{
public partial class Hello
{
public void DoSomething() { }
}
}
file2.cs
namespace Names
{
public partial class Hello
{
public void Go() { DoSomething(); }
}
}
Although what other people say about partial classes is true. I'd also suggest you to analyze refactoring opportunities on your class.
If you're having problems to manage it, you could try to split your single class in several classes with less responsibilities.
IMHO partial classes may not help very much. Do you have your class separated in regions? Regions improve the readability of your code.
Yes you can split any partial class across as many files as you like.
Strip out each decent size class into at least one file. Wrap each class in the same namespace.
For large classes use either:
a. Region blocks eg
#region // Members
int my_int;
// other members...
#endregion
b. partial keyword to break a single class accross several files.

Class Structure w/ LINQ, Partial Classes, and Abstract Classes

I am following the Nerd Dinner tutorial as I'm learning ASP.NET MVC, and I am currently on Step 3: Building the Model. One part of this section discusses how to integrate validation and business rule logic with the model classes. All this makes perfect sense. However, in the case of this source code, the author only validates one class: Dinner.
What I am wondering is, say I have multiple classes that need validation (Dinner, Guest, etc). It doesn't seem smart to me to repeatedly write these two methods in the partial class:
public bool IsValid
{
get { return (GetRuleViolations().Count() == 0); }
}
partial void OnValidate(ChangeAction action)
{
if (!IsValid)
{
throw new ApplicationException("Rule violations prevent saving.");
}
}
What I'm wondering is, can you create an abstract class (because "GetRuleViolations" needs to be implemented separately) and extend a partial class? I'm thinking something like this (based on his example):
public partial class Dinner : Validation {
public IEnumerable<RuleViolation> GetRuleViolations() {
yield break;
}
}
This doesn't "feel" right, but I wanted to check with SO to get opinions of individuals smarter than me on this. I also tested it out, and it seems that the partial keyword on the OnValidate method is causing problems (understandably so). This doesn't seem possible to fix (but I could very well be wrong).
Thanks!
I'm wondering is, can you create an
abstract class ... and extend a
partial class?
Sure, the partial keyword simply indicates that the class is implemented in multiple files - it has no real bearing on inheritance ... except in one narrow respect:
If the partial class contains a
reference to a forward-declared
partial method, but no part of that
class implements that partial method -
all calls to that partial method will
be omitted by the compiler.
So what does this mean. If your partial class declares a partial method in one of it's parts, but no other part of your class defines the partial method - then you can't call that partial method in any derived classes ... since it won't exist.
Let's look at an example:
// file1.cs (code gen'd)
public partial class Validation {
partial void OnValidate(ChangeAction action);
private void SomeMethod() {
OnValidate( ChangeAction.Whatever );
}
}
// file2.cs (Validation class body)
public partial class Validation {
//partial void OnValidate(ChangeAction action) { ... }
}
public class Dinner : Validation {
public void SomeOtherMethod() {
OnValidate(null); // won't compile ... OnValidate doesn't exist
}
}
You should also be aware that partial methods cannot have modifiers (like new, abstract, virtual, public, private, etc). This means you cannot override a partial method in a derived class. You can, however, define a virtual method that a partial method calls.
To your general question, there's nothing wrong with inheriting from partial classes or trying to avoid duplication of code. However, you need to work within the one or two limitations that partial classes/methods impose.
In your example, if you want to avoid duplicating logic, you may need to define your partial methods in the base class to make sure they are always available. Derived classes would not be be able to override them - but if this is needed, then just don't make those methods partial.

Categories

Resources