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.
Related
I have a class Employee.cs that was autogenerated by EntityFramework when i connected to a database, now i want to implement a partial class but I can't use "Employee.cs" name for that class because it already exists. Can I give other name to it and it will work? Can you explain how the compiler will know that there is another partial class of Employee.cs?
You can give the file whatever name you want like Employee.custom.cs but you have to call the class in it Employee in the same namespace as the Employee class in the other file, also with a partial modifier, and you should be good to go.
The compiler just gathers all the partial classes with the same name and compiles it into one class per name.
Compiler always works with fullname of class. If there is a project named MyProject, full name for the class would be something like:
MyProject.Employee
If You want to create class with the same name, You have to add a level of separation in naming, or if it have to be partial class with this generated class, You have to mark it also as a partial.
You can either create (in Model/Employee.cs):
public class MyProject.AnySubPath.Employee {}
Or:
In file Model/Employee.cs
public partial class MyProject.Employee {}
In file ViewModel/Employee.cs
public partial class MyProject.Employee {}
Important for You is to realize what is the partial mean & what will the compiler to with Your class: In fact the compiler will just put all the partial classes together and then compile them. Only benefit from being partial is that You can have the code split among multiple files. Excelent example for this is Windows.Forms, where You have "code-behind" file (Form1.cs) and then You have "designer" file (Form1.Designer.cs).
Also You can name the files whatever name You want, it is just common standard to have 1 class = 1 file and the class name should fit the file name.
It would be great if this would work. Am I trying to implement my idea in the wrong way?
I would like to use partial method, to be able to extend existing code, and simply plug in/out implementation of methods.
Basically exactly what the reference is stating:
Partial methods enable class designers to provide method hooks,
similar to event handlers, that developers may decide to implement or
not. If the developer does not supply an implementation, the compiler
removes the signature at compile time.
My first try of using this is the following:
DefinitionsBase.cs:
namespace ABC {
public partial class Definitions {
// No implementation
static partial void TestImplementaion();
}
}
DefinitionsExt.cs:
namespace ABC {
public partial class Definitions {
static partial void TestImplementaion(){
// Implementation is here
}
}
}
Program.cs:
namespace ABC {
class Program {
static void Main(string[] args) {
Definitions.TestImplementaion();
}
}
}
It's same namespace, but as reference states partial methods are implicitly private. It doesn't accept access modifiers and I cannot call it from my class. Is there a way to use it as I intend to?
Thanks!
You could use a public method that calls the private method, but I am not sure if this is what you want. This just makes your code work.
Partial methods are by definition private so as during compilation time, in case the method was not implemented, the compiler does not need to go through all of the code, find all possible references to the method, and remove them.
This is a design choice since partial methods do not necessarily need to be implemented, the compiler only looks in the partial class implementation and not throughout all of the code.
If you implement a public method that calls the partial method and the partial method was not implemented, the compiler will still only look in the partial class files and code, even though you have access to that partial method from anywhere in your code.
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).
Hi I have a partial class which reads a value from in
public partial class getFile : System.Web.UI.Page
{
string file = AcceptButton.FileName;
}
string file I want to access in a regular class
public class
{
string _file=file;
}
First class being partial class I cant do that. How can I do this?
First class being partial class I cant do that. How can I do this?
The fact that the class is partial has nothing to do with this. From the point of view of an external type it doesn't know (or care) that the class is a partial class.
The reason you can access file from some other class is that file is private.
To access the member directly you would need that member to be public, and you'd also need an instance of that type.
Having said that, since it seems this is related to as webpage, it doesn't make sense for some other class to be accessing the pages fields in the first place. What you should be doing is having the constructor or method(s) of test accept a parameter of type string to which getFile can pass in it's file field when either creating a test object or calling one of its methods.
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.