C# Class Definitions - Which Keyword? - c#

I'm not entirely sure about this. Is it 'static'?

The keyword you're looking for is partial.
https://msdn.microsoft.com/en-us/library/wa80x488.aspx

Yes partial is needed, but you also need abstract on the methods and the classes or it still won't compile because non-abstract methods must declare a body.

No It's not static. You need Partial Class. Also You need to provide body to your functions.
It is possible to split the definition of a class or a struct, an
interface or a method over two or more source files. Each source file
contains a section of the type or method definition, and all parts are
combined when the application is compiled.
To split a class definition, use the partial keyword modifier.
See Below example:
public partial class Employee
{
public void DoWork()
{
}
}
public partial class Employee
{
public void GoToLunch()
{
}
}

Related

How to extend System.Windows.Input.Keyboard class

I would like to add some additional methods to System.Windows.Input.Keyboard.I have tried to create a partial class like this;
namespace System.Windows.Input
{
public static partial class Keyboard
{
//some code...
}
}
However when I try this Resharper informs me that this is not a partial file and when I try to use it I get an ambiguous reference error although both Keyboards are shown as being in the same namespace. Is what I'm trying to do even possible and if not, why not?
No, it's not possible. Keyboard is a static class.
Static classes cannot be instantiated and they cannot be extended.
You can always write your own (static) class and put your methods in there.
You shouldn't use the same namespace as Keyboard, the class should be only static, you can name the class whatever you want "KeyboardExtensions" for exemple
See this for extension methods https://msdn.microsoft.com/en-us/library/bb383977.aspx
What you are trying to do is not possible because the Keyboard class is not partial to begin with.
The ambiguous reference is caused by the fact that you're creating a class that already exists in the same namespace so the compiler doesn't know which one to use.
You cannot create a static class that inherits from another static class as suggested by #harmoniemand. Static classes can only inherit from Object.
And you cannot create extension methods on a static class as #Hamza_L seems to be suggesting because you can't use static types as parameters in extension methods.
with a look at the manual, you could see that the System.Windows.Input.Keyboard is not defined as partial (look here) so you are not able to extend it this way.
The better way to do it, is to write an inherited class.
namespace MyApplication.Wrapper
{
public static class MyKeyboard : System.Windows.Input.Keyboard
{
//some code...
}
}

Foward Declarations in C#

I really like declaring all of my methods at the start of a class and would like to do so with forward declarations and then implement them further down. Is this possible in C#?
Ex:
private void Test();
private void Test()
{
}
Yes you can do this. Or you can kinda sorta do this. But for each of these possible "Solutions", if it is for cosmetic reasons only don't use these constructs.
One trick is to use a partial class with partial methods.
partial class A
{
partial void OnSomethingHappened(string s);
}
// This part can be in a separate file.
partial class A
{
/* Comment out this method and the program
will still compile.*/
partial void OnSomethingHappened(string s)
{
Console.WriteLine("Something happened: {0}", s);
}
}
As highlighted in the referenced documentation, its uses are limited:
A partial method has its signature defined in one part of a partial type, and its implementation defined in another part of the type. 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.
The following conditions apply to partial methods:
Signatures in both parts of the partial type must match.
The method must return void.
No access modifiers are allowed. Partial methods are implicitly private.
As pointed out in #Serv and #StanimirYakimov answers, another "kinda sorta" construct that can be used is the declaration of an interface or pure abstract class, very similar to how you would declare one in c++:
public interface IA
{
int GetTheOneAndOnlyNumber();
}
public abstract class AA
{
protected abstract void OnSomethingHappened(string s);
}
public class A : AA, IA
{
public int GetTheOneAndOnlyNumber()
{
return 42;
}
protected override void OnSomethingHappened(string s)
{
Console.WriteLine(s);
}
}
When switching from a language we know well to a new language, there are always specific idioms and constructs that we will miss. This does not mean that it is wise to try to emulate them with non-idiomatic constructs in the new language.
If you would like to have a condensed view of the structure of your code in Visual Studio, there are several standard ways of doing that, such as the Object Browser and Class View.
And if you search and look around, you will find other available tools that can help you with getting a quick overview of the structure of your code.
You can do it using interfaces
Just define which methods your class will use by inheriting from an interface.
See this interface as a mixture of forward declarations and a contract. Classes inherting from an interface must implement all of its members.
public interface iSomeClass
{
void MyMethod1();
bool MyBoolMethod();
}
public class MyClass : iSomeClass
{
public void MyMethod1()
{
//...
}
public bool MyBoolMethod()
{
//...
return true;
}
}
Simple answer no it is not possible.
The reason is that there are no standalone functions in C# but classes with methods.
Also in other languages like C++ once you start using classes forward declaration of the methods themselves are not needed. It can be that the classes themselves need forward declarations in C++ but since you are talking about methods the comparison still stands.
Bottom line a class is completely defined by its methods in any order they are defined.
You can't really do things like this in C#. I am not sure why you would really want to anyway. Having the declaration and definition in one place is simple and easier to understand
Doing something like this is required in some other languages, but forcing that pattern in C# probably isn't a good idea.
No you can not do it. You can only declare abstract methods like this. Otherwise it will give you an error.
I tried and it gave me
Error 1 'Project.SomeClass.ABC()' must declare a body because it is not marked abstract, extern, or partial
Only abstract methods can be defined like this, abstract methods need only a prototype to be overridden.
This is valid:
public abstract void ABC();
Forward declaration is not possible in C# classes. It's possible only in Interfaces and if your method is abstract. Something like this is allowed
abstract void Draw();

Does C# need the private keyword?

(inspired by this comment)
Is there ever a situation in which you need to use the private keyword?
(In other words, a situation in which omitting the keyword would result in different behavior)
public class Foo
{
public int Bar { get; private set; }
}
Omitting the word 'private' would change the accessibility.
a situation in which omitting the keyword [private] would result in different behavior
David Yaw's answer gave the most usual situation. Here is another one:
In Account_generated.cs:
// Generated file. Do not edit!
public partial class Account
{
...
private partial class Helper
{
...
}
...
}
In AccountHandCoded.cs:
public partial class Account
{
...
public partial class Helper
{
...
}
...
}
The above code will not compile. The first "part" of Account requires the nested class Helper to be private. Therefore the attempt by the hand-coder to make Helper public must fail!
However, had the first part of the class simply omitted the private keyword, all would compile.
So for partial classes (and structs, interfaces), the access-level-free declaration
partial class Name
means "the other 'parts' of this class are allowed to decide what the accessibility should be".
Whereas explicitly giving the default accessibility (which is internal for non-nested types and private for nested ones) means "this class must have the most restricted access possible, and the other 'parts' cannot change that fact".
private isn't about the runtime behaviour. It's to make your application maintainable. What's hidden by private can only ever affect the code outside its class through the public or protected members.
So the answer is 'no' for runtime behaviour, 'yes' for developer behaviour!
In C# version 7.2 and later.
The private protected keyword combination is a member access modifier. A private protected member is accessible by types derived from the containing class, but only within its containing assembly.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/private-protected

Using "partial" on a generic class

I am using a generic class called ViewModelCollection<BaseViewModel> which handles a lists of ViewModels and delivers standard add() and delete() commands.
Now I'm wondering if I can "extend" this class using the partial construct for a certain ViewModel, whose name is, say, CarViewModel.
Is something like this possible?
partial class ViewModelCollection<BaseViewModel>
{
... some command and list stuff ...
}
partial class ViewModelCollection<CarViewModel>
{
... special commands for car view model
}
No, you can't, partial just splits the class definition over multiple files, the definition has to be the same. You need to derive from ViewModelCollection<T>:
public class ViewModelCollection<T> where T: BaseViewModel
{
//methods
}
public class CarViewModelCollection : ViewModelCollection<CarVieModel>
{
//specific methods
}
partial is used only to split a class across multiple source files. The class definition itself must be the same.
Take the partial methods added and create an interface, you can then constrain the generic to use that interface and work off of those methods defined.

Partial classes/partial methods vs base/inherited classes

a question about class design. Currently I have the following structure:
abstract Base Repository Class
Default Repository implementation class (implements some abstract methods, where logic is common thru all of the Specific classes but leaves other empty)
Specific Repository implementation Class (implements what is left empty in the above Default class)
I've now came to the problem where I have a specific Update() method in Specific class but when all the code in this method executes some code from the base Default class should be executed too.
I could do it like this
public override Update()
{
// do Specific class actions and updates
// ....
// follow with base.Update()
base.Update();
}
but this requires those base.XYZ() calls in all the inherited methods. Could I go around that somehow with partials?
So the requirement is to have code in both parent and inherited class (or to make those two one class using partials) and code from method implementation in both places should be executed. Also what about if I wanted to turn it around and execute base class code first followed by the inherited class code?
thanks
Have you considered something like:
public abstract class YourBaseClass
{
public void Update()
{
// Do some stuff
//
// Invoke inherited class's method
UpdateCore();
}
protected abstract void UpdateCore();
}
public class YourChildClass : YourBaseClass
{
protected override void UpdateCore()
{
//Do the important stuff
}
}
//Somewhere else in code:
var ycc = new YourChildClass();
ycc.Update();
All the partial keyword means is that the definition of the class is split between source files:
It is possible to split the definition of a class or a struct, an interface or a method over two or more source files. Each source file contains a section of the type or method definition, and all parts are combined when the application is compiled.
There still has to be a complete definition of the class in the project.
You'd be better off creating a subclass, that way you can override specific methods.
As far as partial methods go (from the same link as above):
A partial method declaration consists of two parts: the definition, and the implementation. These may be in separate parts of a partial class, or in the same part. If there is no implementation declaration, then the compiler optimizes away both the defining declaration and all calls to the method.
// Definition in file1.cs
partial void onNameChanged();
// Implementation in file2.cs
partial void onNameChanged()
{
// method body
}
You can't have half the method in one file and the other half in another.
Here's how you can do this:
public sealed override void Update()
{
UpdateCore();
base.Update();
}
public abstract /* or virtual */ void UpdateCore()
{
// Class-specific stuff
}
Forget about partial, that has entirely different semantics. Whether the overrider of your virtual base class method should call the base class method is not automatic. It needs to be part of your documentation. A good example are the OnXxxx() methods in the Control class, the MSDN library docs have a "Note to implementer" comment that warns that calling the base class method is usually necessary.
If you make the base class method abstract then it is crystal-clear to the overrider. If it is not, you are dropping a strong hint that it ought to be done. If you expect the override to completely replace your base implementation then you should really consider making it abstract. This ambiguity, combined with the odds that the overrider breaks your base class by overriding incorrectly, is definitely one of the weak points of polymorphism.
Add a new virtual (not abstract, since not all specific implementation need to override it?) method to your Default implementation to accommodate inheritors having their own additional steps on top of it's own implementation.
Call the virtual method at the appropriate point in the Default Implementation's abstract method implementation.
You've left your abstract class as it is and transparently grown the flexibility of the default implementation.

Categories